0

I tried to parse a string array using the code below but the required data never printed! could any one tell me how to fix it ?Thanks

$data Array structure :

Array
(
    [js] => Array
        (
            [total_items] => 20
            [max_page_items] => 2
            [selected_item] => 0
            [cur_page] => 0
            [data] => Array
                (
                    [0] => Array
                        (
                        [tmp] => 1
                        [name] => mango
                        [abc] => abcd4 http://mysite/items/1234
                        [number] => 1123
                        [itemCategory_title] => fruits
                        [logo] => 2123.png
                        [itemCategory_id] => 90
                        )
                    [1] => Array
                        (
                        [tmp] => 0
                        [name] => cherry
                        [abc] => abcd4 http://mysite/items/1235
                        [number] => 1124
                        [itemCategory_title] => fruits
                        [logo] => 2124.png
                        [itemCategory_id] => 
                        )

               )

         )

    [text] => no error
)

php code:

<?
$code2 = stripslashes($_POST['outputtext']);

$data = json_decode($code2);

foreach( $data as $item ) {
  echo $item['tmp'];
  echo $item['name'];
  echo $item['abc'];
  echo $item['number'];
  echo $item['itemCategory_title'];
  echo $item['log'];
  echo $item['itemCategory_id'];    
}

?>
2
  • 1
    foreach( $data['js']['data'] as $item ) { Commented Nov 20, 2015 at 18:27
  • First, json_decode returns an object, not an array. Unless you pass true as the second object that is. Both would work though, if using an object, you need to use the arrow operator like $item->tmp. Second, the data key is under the js key. So you need to loop over $data['js']['data'] (or $data->js->data if you leave off that second argument). Commented Nov 20, 2015 at 18:28

1 Answer 1

1

It should be:

foreach ($data['js']['data'] AS $item)

because the array is nested several levels down in $data.

Note that you need to call json_decode($code2, true) to get an associative array like that. By default, it returns an object, not an array, so you would do:

foreach ($data->js->data as $item) {
    echo $item->tmp;
    echo $item->name;
    ...
}
Sign up to request clarification or add additional context in comments.

1 Comment

We get questions like this on a daily basis. I don't understand how you can look at that array structure and not see immediately that the array you want is nested, not at the top level.

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.