Joey de Vries Joey de Vries - 6 months ago 24
JSON Question

PHP Json only a first result

My issue is that when I use

foreach
trough my JSON commands it will only give the first command. In this case HELP but not the second one that is Test.

How can I fix this?

PHP:

echo "Commands:<br>";
$json = file_get_contents("App/cmd/commands.json");
$register = json_decode($json, true);
$command = $_GET["c"];
foreach ($register['commands'] as $key => $value){
echo $key;
if($command == $key)
{
echo "Found!";
return;
}
if(isset($register["commands"][$key]["alias"])){
echo "&nbsp;&nbsp; Has Aliases<Br>";
$aliases = explode(",", $register["commands"][$key]["alias"]);
foreach ($aliases as $alias)
{
if($command == $alias)
{
echo "Found!";
return;
}
}
}
echo "Not Found!";
return;
}


My Json:

{"help":"value","commands":{"help":{"function":"test"},"test":{"function":"test"}}}

Answer

Because you have return; everywhere. Then you can't have a second iteration, because you always finish the process. Remove the return according to your logic to have a second iteration and make proper refactor to your code, to make it functional.

Comments