[英]Assign values in JSON array to variables in PHP
I have a query that upon being JSON encoded, and print_r()
looks like this: 我有一个查询,在进行JSON编码时, print_r()
看起来像这样:
Array
(
[response] => Array
(
[numFound] => 2392
[start] => 0
[maxScore] => 1
[docs] => Array
(
)
)
[stats] => Array
(
[stats_fields] => Array
(
[q_one] => Array
(
[min] => 0.0059
[max] => 6.0095
[count] => 2392
[missing] => 0
[sum] => 53.9131
[sumOfSquares] => 48.16448107
[mean] => 0.022538921404682
[stddev] => 0.14012800795752
[facets] => Array
(
)
)
[q_two] => Array
(
[min] => 0
[max] => 0.0075
[count] => 2392
[missing] => 0
[sum] => 17.67
[sumOfSquares] => 0.132525
[mean] => 0.0073871237458194
[stddev] => 0.00091333432809989
[facets] => Array
(
)
)
[q_three] => Array
(
[min] => 0
[max] => 0.065
[count] => 2392
[missing] => 0
[sum] => 153.14
[sumOfSquares] => 9.9541
[mean] => 0.064021739130435
[stddev] => 0.0079155641768643
[facets] => Array
(
)
)
)
)
)
Within stats >> stats_fields
I want to write a foreach
loop that captures the names of each header: q_one
, q_two
, and q_three
, but I'm not sure how to do that. 在stats >> stats_fields
我想编写一个foreach
循环来捕获每个头的名称: q_one
, q_two
和q_three
,但我不知道该怎么做。
I can capture the elements inside each of these 3 'headers', because their names are static, (eg - each one has a min
and a max
element) 我可以捕获这3个'标题'中的每个元素,因为它们的名称是静态的(例如 - 每个都有一个min
和max
元素)
foreach ($json['stats']['stats_fields'] as $j) {
echo $j['min']
}
but I'm not sure how to get the header names... 但我不知道如何获得标题名称......
Get them in an array with array_keys()
: 使用array_keys()
它们放入数组中:
$headers = array_keys($json['stats']['stats_fields']);
Or get them in the loop if you need it there using $key => $value
syntax: 或者如果你需要使用$key => $value
语法将它们放入循环中:
foreach ($json['stats']['stats_fields'] as $key => $j) {
echo $key;
echo $j['min'];
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.