0

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"}}}
2
  • 2
    "alias" is not in your sample data Commented May 22, 2016 at 14:55
  • What are you passing in $_GET["c"] Commented May 22, 2016 at 15:00

2 Answers 2

3

It is because you set

   echo "Not Found!"; return;

in the loop so there is no chance for second iteration. That code should be after loop not inside.

Sign up to request clarification or add additional context in comments.

Comments

2

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.

1 Comment

Thanks for the suggestion, I will make the change!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.