如何从json解码数组访问值

时间:2016-06-07 06:49:44

标签: javascript php json

JSON解码:

$test=json_decode($tableData,TRUE);

结果是:

 [{
    "IngredientName": "Sunflower",
    "Quantity": "6",
    "Free_Quantity": "0",
    "Rate": "6"
}, {
    "IngredientName": "ganapathi",
    "Quantity": "6",
    "Free_Quantity": "0",
    "Rate": "6"
}]

如何使用IngredientName循环从结果数组的每个元素访问for..each

5 个答案:

答案 0 :(得分:0)

试试这个:

$test=json_decode($tableData);
foreach($test as $arr) {
  echo $arr->IngredientName."<br />";
}

答案 1 :(得分:0)

解码JSON的结果是一个数组数组。您可以通过以下方式迭代它们:

$test=json_decode($tableData,TRUE);
foreach($test as $ingredient) {
  echo $ingredient['IngredientName'] . '<br />';
}

答案 2 :(得分:0)

这可能是一种有效的方法:

<?php
$encoded = '[{"IngredientName":"Sunflower","Quantity":"6","Free_Quantity":"0","Rate":"6"},{"IngredientName":"ganapathi","Quantity":"6","Free_Quantity":"0","Rate":"6"}]';
$decoded = json_decode($encoded);

foreach ($decoded as $object) {
  var_dump($object->IngredientName);
}

明显的输出是:

string(9) "Sunflower"
string(9) "ganapathi"

答案 3 :(得分:0)

尝试这样的事情

foreach($tableData as $value){
echo json_decode($value['IngredientName']);
}

答案 4 :(得分:0)

$array=json_decode($tableData,TRUE);  
foreach ($array as $key => $value) {
     echo $value['IngredientName'] . '<br />';
}