2016-01-26 64 views
0

我有一個具有以下結構的JSON。通過JSON循環並將值存儲到PHP數組中

{ 

"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數組,單價成另一個,數量到另一個和價格到另一個。我怎麼做?

+2

[json_decode()](http://php.net/manual/en/function.json-decode.php),然後使用[array_column()](http://php.net/manual/en/ function.array-column.php) –

+0

我不知道如何在這裏使用array_column。你可以請秀嗎? –

+1

[演示使用array_column](https://3v4l.org/kP2C7) –

回答

0

經過一番研究,我發現,這裏解決我的問題最efficientt辦法是做類似下面。

$cash=json_decode($new_json, true); 

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

等等。

這可以很容易地放入循環,取入HTML文本字段(正如我在這裏的情況下),等等。

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)); 
1
$getArray = get_object_vars(json_decode($json)); 
print_r($getArray); 
echo $getArray[1]->Itemname; 
echo $getArray[1]->unitprice; 

您需要get_object_vars以及爲實現您的要求。

0

您需要通過PHP的json_decode()

$decodeJson將返回對象以您的JSON解碼,那麼你可以通過使用$val->Itemnameforeach

$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

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']; 
} 

閱讀Itemname和其他價值或Php = 5.5

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

@MarkBaker謝謝,糾正。 – Progrock

0

試一下:

$json = json_decode($json); 

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

} 
+0

雖然這段代碼片段可能回答OP的問題,但如果你解釋爲什麼它解決了這個問題,這個答案會對未來的訪問者更有用。 –