我在数组学习,我想知道如何添加这种数组的键?
{
"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,它会返回错误.
Uncaught Error: Cannot use object of type stdClass as array
我真的可以在这里使用一些解释
解决方法:
你根本不需要循环.您可以使用array_column将数组与一行代码相关联.
$cart_array['items'] = array_column($cart_array['items'], NULL, 'cart_id');
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。