1

Hello I have decoded a json string that I sent to my server and Im trying to get the values from him.

My problem is that I cant get the values from the inner arrays.

This is my code:

<?php

    $post = file_get_contents('php://input');

    $arrayBig = json_decode($post, true);

    foreach ($arrayBig as $array)
    {


    $exercise = $array['exercise'];

    $response["exercise"] = $exercise;
    $response["array"] = $array;

    echo json_encode($response);


    }

?>

When I get the answer from my $response I get this values:

{"exercise":null,"array":[{"exercise":"foo","reps":"foo"}]}

Why is $array['exercise'] null if I can see that is not null in the array

Thanks.

2
  • 1
    You should do a var_dump($arrayBig). You'll probably see you have another array in your array. Commented Feb 19, 2014 at 22:33
  • I suggest you enable display_errors and set error_reporting to E_ALL. You have an undefined index error for $array['exercise'] Commented Feb 19, 2014 at 22:37

2 Answers 2

2

From looking at the result of $response['array'], it looks like $array is actually this

[['exercise' => 'foo', 'reps' => 'foo']]

that is, an associative array nested within a numeric one. You should probably do some value checking before blindly assigning values but in the interest of brevity...

$exercise = $array[0]['exercise'];
Sign up to request clarification or add additional context in comments.

Comments

2

Because of the [{...}] you are getting an array in an array when you decode your array key.

So:

$exercise = $array['exercise'];

Should be:

$exercise = $array[0]['exercise'];

See the example here.

Comments

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.