我正在研究数组,我想知道如何为这种数组添加密钥?
{
"items":[
{
"count":"1",
"id":123,
"description":"Bag",
"price":11
},
{
"count":1,
"id":1234,
"description":"10% Discount",
"price":-1.1
}
],
"total":9.9,
"discount_total":9.9
}
因为我需要转换数组以使其具有基于数组内ID的键。
{
"items":{
"123":{
"count":"1",
"cart_id":123,
"description":"Bag",
"price":11
},
"1234":{
"count":1,
"cart_id":1234,
"description":"10% Discount",
"price":-1.1
}
},
"total":9.9,
"discount_total":9.9
}
这是我的代码
header('Content-Type: application/json');
$cart_array = json_decode('{
"items":[
{
"count":"1",
"cart_id":123,
"plu":"TP16",
"description":"Bag"
},
{
"count":1,
"cart_id":1234,
"plu":"DISCT10",
"description":"10% Discount"
}
],
"total":9.9,
"discount_total":9.9
}');
foreach ($cart_array->items as $item)
{
$construct["cart_id"] = $item->cart_id;
}
我想问一下如何将id放入数组中?我无法使用$cart_array['id'] = $value
,它返回错误。
未捕获的错误:无法将stdClass类型的对象用作数组
我真的可以在这里使用一些解释
答案 0 :(得分:2)
以下代码可以为您提供帮助。
<?php
$json = '{
"items":[
{
"count":"1",
"cart_id":123,
"plu":"TP16",
"description":"Small Four Seasons"
},
{
"count":1,
"cart_id":1234,
"plu":"DISCT10",
"description":"10% Discount"
}
],
"total":9.9,
"discount_total":9.9
}';
$data = json_decode($json,TRUE); //json decode
foreach ($data['items'] as $key => $value)
{
$data['items'][$value['cart_id']] = $value;
unset($data['items'][$key]);
}
echo "<pre>";print_r($data);die;
?>
答案 1 :(得分:1)
您可以在应用程序中使用此代码向索引数组添加键。
foreach($obj as $key=>$val){
foreach ($val as $index=>$content){
$data[$content['id']]=$content;
}
}
答案 2 :(得分:1)
您可以根据需要获取相同的输出json数据:
$array = json_decode($data,true);
if(isset($array['items']) && count($array['items']) > 0){
foreach($array['items'] as $key => $value){
$value['cart_id'] = $value['id'];
unset($value['id']);
$array['items'][$value['cart_id']] = $value;
unset($array['items'][$key]);
}
}
echo "<pre>";print_r($array);
echo json_encode($array);
答案 3 :(得分:1)
您根本不需要循环。您可以使用array_column使数组与一行代码关联。
$cart_array['items'] = array_column($cart_array['items'], NULL, 'cart_id');