【问题标题】:Get associative array values into variables,which is in string format from cookies将关联数组值获取到变量中,该变量是 cookie 中的字符串格式
【发布时间】:2015-02-28 04:20:25
【问题描述】:

我从字符串格式的 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 搜索,我需要接收其值数量=3 和价格-1500 和标题鞋

我在这里尝试过但失败了-

for($i=0;$i<sizeof($ar);$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

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

【问题讨论】:

    标签: php jquery arrays json associative-array


    【解决方案1】:

    使用json_decode($getcart, true);。这里json_decode() 中的true 参数将JSON 转换为数组。如果没有true 参数,它将转换为array()object

    $getcart = '[{"id":"7","quantity":"3","price":1500,"title":"Shoes"},{"id":"9","quantity":"4","price":1290,"title":"Shirt"}]';
    $arr = json_decode($getcart, true);
    
    print '<pre>';
    foreach($arr as $val){
        print_r($val);
        //print $val['id'];
        //print $val['quantity'];
        //print $val['price'];
        //print $val['title'];
    }
    print '</pre>';
    

    【讨论】:

    • 谢谢+1,它给出了我想要的答案,for($i=0; $i&lt; count($arr); $i++) { print_r($arr[$i]['id']); print_r($arr[$i]['quantity']); print_r($arr[$i]['title']); }
    猜你喜欢
    • 1970-01-01
    • 2013-10-04
    • 2013-05-02
    • 1970-01-01
    • 2020-11-06
    • 2016-10-11
    • 2018-12-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多