2015-11-08 46 views
-4

如何循環瀏覽PHP中的json_decode($ json_emp)輸出並獲取值?如何在PHP中循環訪問這些值

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

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

需要找到獲取ID和名稱的個人值。這是數組。

$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 
       ) 

     ) 

) 

這裏是對象;

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 
       ) 

     ) 

) 

請讓我知道如何遍歷這些並獲得值。試了很多,感到困惑。

+4

http://php.net/manual/en/control-structures.foreach.php – Streetlamp

+0

而另:http://stackoverflow.com/q/15607029/1065197 –

回答

1

如果你想使用對象,試試這個:

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

對於數組:

foreach ($array_tmp['info'] as $emp) 
{ 
    echo $emp['name']; 
} 
1

使用此

$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;  
} 

上面的代碼輸出

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

DEMO

,如果你處理object而不是array

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

將輸出與上面相同。

DEMO