php 把关联数组转为变量,php-将关联数组值转换为变量,该变量是cookie中的字符串格式...

本文介绍了如何从JSON字符串转换为PHP数组,并通过ID检索所需值。问题涉及使用`json_decode()`函数,当传递`true`作为第二个参数时,它将返回关联数组而不是对象。通过遍历解码后的数组,可以轻松地按ID查找并打印所需的商品属性。
摘要由CSDN通过智能技术生成

我从字符串格式的Cookie中获取了这种关联的数组类型值-

[{"id":"7","quantity":"3","price":1500,"title":"Shoes"},{"id":"9","quantity":"4","price":1290,"title":"Shirt"}]

var_dump($getcart); // return of this is(just to confirm) -

string(111) "[{"id":"7","quantity":"3","price":1500,"title":"Shoes"},{"id":"9","quantity":"4","price":1290,"title":"Shirt"}]"

如果我将其转换为数组-

json_encode($getcart);

通过-将其带到另一个数组以进行进一步的操作-

$ar=array();

$ar = json_decode($getcart);

我需要帮助-

通过其“ id”获取所有值.对于前.如果我按id = 7搜索,则需要接收其值quantity = 3,price-1500和title-shoes

我在这里尝试过并失败了

for($i=0;$i

{

print_r(array_values($ar[1])); // gives back ----> Array ( [0] => stdClass Object ( [id] => 7 [quantity] => 3 [price] => 1500 [title] => casual blue strip ) [1] => stdClass Object ( [id] => 9 [quantity] => 4 [price] => 1290 [title] => United Colors of Benetton shirt ) ) Array ( [0] => stdClass Object ( [id] => 7 [quantity] => 3 [price] => 1500 [title] => casual blue strip ) [1] => stdClass Object ( [id] => 9 [quantity] => 4 [price] => 1290 [title] => United Colors of Benetton shirt ) )

}

echo $ar // gives ------> ArrayArray

这是有效的回报,但不是我想要的.这里有任何帮助来分别获取值吗?

解决方法:

使用json_decode($getcart,true);.此处json_decode()中的true参数将JSON转换为数组.如果没有true参数,则将其转换为object的array().

$getcart = '[{"id":"7","quantity":"3","price":1500,"title":"Shoes"},{"id":"9","quantity":"4","price":1290,"title":"Shirt"}]';

$arr = json_decode($getcart, true);

print '

';

foreach($arr as $val){

print_r($val);

//print $val['id'];

//print $val['quantity'];

//print $val['price'];

//print $val['title'];

}

print '';

标签:associative-array,arrays,json,php,jquery

来源: https://codeday.me/bug/20191120/2047463.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值