-5

How to to loop through the json_decode($json_emp) output in PHP and get the values ?

    $array_emp = json_decode($json_emp);
    var_dump( $array_emp)

        {"info":[{"id":"10","name":"employee1"},{"id":"11","name":"employee2"},{"id":"12","name":"emplyee3"}]}

Need to find get the individual values of ID and name . Here is the array.

$array_emp = json_decode($json_emp,true);

Array
(
    [info] => Array
        (
            [0] => Array
                (
                    [id] => 10
                    [name] => employee1
                )

            [1] => Array
                (
                    [id] => 11
                    [name] => employee2
                )

            [2] => Array
                (
                    [id] => 12
                    [name] => emplyee3
                )

        )

)

Here is the objects ;

stdClass Object
(
    [info] => Array
        (
            [0] => stdClass Object
                (
                    [id] => 10
                    [name] => employee1
                )

            [1] => stdClass Object
                (
                    [id] => 11
                    [name] => employee2
                )

            [2] => stdClass Object
                (
                    [id] => 12
                    [name] => emplyee3
                )

        )

)

Please let me know how to loop through these and get the values . Tried a lot and got confused .

Learner
  • 130
  • 12

2 Answers2

1

If you want to use objects, try this:

foreach ($array_tmp->info as $emp)
{
    echo $emp->name;
}

For arrays:

foreach  ($array_tmp['info'] as $emp)
{
    echo $emp['name'];
}
rjdown
  • 8,530
  • 3
  • 23
  • 39
1

Use this

$json = '{"info":[{"id":"10","name":"employee1"},{"id":"11","name":"employee2"},{"id":"12","name":"emplyee3"}]}';

$json = json_decode($json, TRUE);
foreach($json['info'] as $info){
    echo 'ID: '.$info['id'].PHP_EOL;    
    echo 'Name: '.$info['name'].PHP_EOL;    
}

above code outputs

ID: 10
Name: employee1
ID: 11
Name: employee2
ID: 12
Name: emplyee3

DEMO

and if you process object rather than array

$json = json_decode($json);
foreach($json->info as $info){
    echo 'ID: '.$info->id.PHP_EOL;  
    echo 'Name: '.$info->name.PHP_EOL;  
}

will output the same as above.

DEMO

Mubin
  • 3,597
  • 4
  • 28
  • 49