解码 JSON 字符串


Decode a Json string

想知道我如何在 php 中提取 json 的索引部分。多年来一直困扰着我。谢谢!

$ch = curl_init('https://domain.com/blah/blah');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_BINARYTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
$promo = curl_exec($ch);
curl_close($ch);
$promo = json_decode($promo, true);

.

{"something":"blahhhh","name":"bob!","id":"7","select":[{"Index":1,"code":"a1","name":"hello","description":"more text"},{"Index":2,"code":"a2","name":"bye","description":"test.."},{"Index":3,"code":"a3","name":"ayeee","description":"Morning!"},{"Index":4,"code":"a4","name":"Cheese!","description":"Yummy!"},{"Index":5,"code":"a5","name":"Water","description":"why is it cloudy? :( "}],"chant":"Free the ducks!","joined":"2015-01-01T16:49:05.000+0000","cool":false}

当 json_decode 的第二个参数设置为 true 时,该函数将返回一个非常接近 JSON 结构的关联数组。

从那里,您所要做的就是将 JSON 路径放回关联的 php 数组中以访问所需的值!

foreach($promo['select'] as $select){
    echo $select['Index'].' ';
}

例 : http://codepad.org/OMg7WTr0

如果您希望提取其他值并且您没有弄清楚路径,只需var_dump($promo);它将为您提供要使用的数组路径的清晰视图