我正在尝试遍历JSON多维数组,并为每个商店获取最低的distance
值,并将其与location_id
值一起打印。
除了这里我所没有的,我无所不能。我已经尝试通过搜索stackoverflow来尝试一百万个选项,但无法弄清楚我在做什么错。
我的JSON数据如下:
$json = '{
"shops": [
{
"shop_id": "100",
"locations": [
{ "location_id": "100_1", "distance": "10.3" },
{ "location_id": "100_2", "distance": "15.2" }
]
},
{
"shop_id": "101",
"locations": [
{ "location_id": "101_1", "distance": "19.3" },
{ "location_id": "101_2", "distance": "12.4" }
]
}]
}';
现在,我的代码是:
// Decode the JSON data
$json_data = json_decode($json,true);
// Do a foreach loop
foreach($json_data['shops'] as $shops){
echo $shops['shop_id'].', ';
// Currently prints:
// 101, 102 ,
// But I need it to print:
// 100_1 -> 10.3, 101_2 -> 12.4
}
我尝试将另一个foreach循环放入现有循环中,但是只打印出1
。
我该如何实现?我不能把头缠住它。我需要为每个distance
['shop_id']['locations']
值
答案 0 :(得分:5)
您可以使用array_column
提取特定商店的所有距离,然后在该数组上使用min
以获取最低值。为了获得位置,我们然后使用array_search
来找到具有该值的最小键,并使用它来为商店获取合适的location_id
:
foreach($json_data['shops'] as $shops) {
$distances = array_column($shops['locations'], 'distance');
$locations = array_column($shops['locations'], 'location_id');
$min = min($distances);
$location = array_search($min, $distances);
echo $locations[$location] . ' -> ' . $min . "\n";
}
输出:
100_1 -> 10.3
101_2 -> 12.4
更新
正如@Andreas在评论中指出的那样,我们可以使用array_column
的第三个参数以其location_id
为键来获取距离数组。然后,我们可以对数组进行排序,并使用current
和key
获得最小距离和相应的位置:
foreach($json_data['shops'] as $shops) {
$distances = array_column($shops['locations'], 'distance', 'location_id');
asort($distances);
echo key($distances) . ' -> ' . current($distances) . "\n";
}
输出:
100_1 -> 10.3
101_2 -> 12.4
答案 1 :(得分:0)
您可以使用子循环来尝试选择最小距离。易于遵循代码并构造结果数组:
<?php
$json = '{
"shops": [
{
"shop_id": "100",
"locations": [
{ "location_id": "100_1", "distance": "10.3" },
{ "location_id": "100_2", "distance": "15.2" }
]
},
{
"shop_id": "101",
"locations": [
{ "location_id": "101_1", "distance": "19.3" },
{ "location_id": "101_2", "distance": "12.4" }
]
}]
}';
$data = json_decode($json, true);
$min_distances = [];
foreach($data['shops'] as $shop)
{
$distance = null;
foreach($shop['locations'] as $location)
{
if(is_null($distance) || $location['distance'] < $distance)
{
$distance = $location['distance'];
$location_id = $location['location_id'];
}
}
$min_distances[] = [
'shop_id'=>$shop['shop_id'],
'distance'=>$distance,
'location_id'=>$location_id
];
}
var_dump($min_distances);
输出:
array(2) {
[0]=>
array(3) {
["shop_id"]=>
string(3) "100"
["distance"]=>
string(4) "10.3"
["location_id"]=>
string(5) "100_1"
}
[1]=>
array(3) {
["shop_id"]=>
string(3) "101"
["distance"]=>
string(4) "12.4"
["location_id"]=>
string(5) "101_2"
}
}