循环访问JSON并将值存储到PHP数组

时间:2016-01-26 11:17:24

标签: php arrays json

我有一个具有以下结构的JSON。

{

 "1":{"Itemname":"dtfg","unitprice":"12","Qty":"4","price":"$48.00"},
 "2":{"Itemname":"kjh","unitprice":"45","Qty":"7","price":"$315.00"},
 "3":{"Itemname":"yjk","unitprice":"76","Qty":"8","price":"$608.00"},
 "4":{"Itemname":"hgj","unitprice":"4","Qty":"45","price":"$180.00"}

}

我需要将Itemname设置为PHP数组,将Unitprice设置为另一个,将数量设置为另一个,并将价格设置为另一个。我该怎么做?

6 个答案:

答案 0 :(得分:1)

$getArray   = get_object_vars(json_decode($json));
print_r($getArray);
echo $getArray[1]->Itemname;
echo $getArray[1]->unitprice;

您需要get_object_vars才能达到您的要求。

答案 1 :(得分:1)

<?php
$json =<<<JSONLIVES
{
     "1":{"Itemname":"dtfg","unitprice":"12","Qty":"4","price":"$48.00"},
     "2":{"Itemname":"kjh","unitprice":"45","Qty":"7","price":"$315.00"},
     "3":{"Itemname":"yjk","unitprice":"76","Qty":"8","price":"$608.00"},
     "4":{"Itemname":"hgj","unitprice":"4","Qty":"45","price":"$180.00"}
}
JSONLIVES;


$items = json_decode($json, TRUE);

$item_names = array();
foreach($items as $key => $item) {
    $item_names[] = $item['Itemname'];
}

或Php> = 5.5

print_r(array_column($items, 'Itemname'));

答案 2 :(得分:0)

您需要一个名为json_decode()的函数将json数据转换为PHP array

$json =  {

 "1":{"Itemname":"dtfg","unitprice":"12","Qty":"4","price":"$48.00"},
 "2":{"Itemname":"kjh","unitprice":"45","Qty":"7","price":"$315.00"},
 "3":{"Itemname":"yjk","unitprice":"76","Qty":"8","price":"$608.00"},
 "4":{"Itemname":"hgj","unitprice":"4","Qty":"45","price":"$180.00"}

};
var_dump(json_decode($json));

答案 3 :(得分:0)

您需要通过PHP json_decode()

解码您的Json

$decodeJson将返回对象,然后您可以使用Itemname循环中的$val->Itemname来阅读foreach和其他值

$json =  '{

 "1":{"Itemname":"dtfg","unitprice":"12","Qty":"4","price":"$48.00"},
 "2":{"Itemname":"kjh","unitprice":"45","Qty":"7","price":"$315.00"},
 "3":{"Itemname":"yjk","unitprice":"76","Qty":"8","price":"$608.00"},
 "4":{"Itemname":"hgj","unitprice":"4","Qty":"45","price":"$180.00"}

}';

$decodeJson = json_decode($json);

foreach($decodeJson as $key=>$val) {

      print_r($val);
}

Live Json decode

答案 4 :(得分:0)

试试:

$json = json_decode($json);

foreach($json as $obj){
   echo $obj->name;
   .....

}

答案 5 :(得分:0)

经过一番研究,我发现在这里解决我问题的最有效方法是做如下事情。

$cash=json_decode($new_json, true);

echo $arr3[1]['Itemname'];
echo $arr3[1]['unitprice'];
:
:

等等。

这可以很容易地放入循环中,提取到HTML文本字段中(正如我在这个场景中所要求的那样)等等。