如何根据max和min键值排列json数组?

时间:2017-01-17 07:19:31

标签: php arrays json

我需要一个帮助。我有一个json数组,我需要使用PHP按照最大或最小键值重新排列它。我在下面解释我的代码。

$data=array(array("day1"=>1,"day2"=>1,"name"=>"Ram"),array("day1"=>1,"day2"=>2,"name"=>"Raj"),array("day1"=>1,"day2"=>3,"name"=>"Rahul"),array("day1"=>2,"day2"=>3,"name"=>"Rocky"));
echo json_encode($data);

它的输出将如下所示。

[{"day1":1,"day2":1,"name":"Ram"},{"day1":1,"day2":2,"name":"Raj"},{"day1":1,"day2":3,"name":"Rahul"},{"day1":2,"day2":3,"name":"Rocky"}]

这里我在每条记录中都有day1 and day2的不同值。我需要它为每条记录计算day1的最小值和day2的最大值,我的预期输出应如下所示。

预期产出:

[{"day1":1,"day2":3,"name":"Ram"},{"day1":1,"day2":3,"name":"Raj"},{"day1":1,"day2":3,"name":"Rahul"},{"day1":1,"day2":3,"name":"Rocky"}]

2 个答案:

答案 0 :(得分:2)

这会有所帮助 -

liftM null id :: Foldable t => t a -> Bool

<强>输出

$data=array(array("day1"=>1,"day2"=>1,"name"=>"Ram"),array("day1"=>1,"day2"=>2,"name"=>"Raj"),array("day1"=>1,"day2"=>3,"name"=>"Rahul"),array("day1"=>2,"day2"=>3,"name"=>"Rocky"));
// Get all values for day1 & day2 and store them in one array
$values = array_merge(array_column($data, 'day2'), array_column($data, 'day1'));
// Assign values
$data = array_map(function($d) use($values) {
    // Assign the minimum value
    $d['day1'] = min($values);
    // assign the maximum value
    $d['day2'] = max($values);
    return $d;
}, $data);

echo json_encode($data);

答案 1 :(得分:0)

这会有所帮助:查看 demo

    $data=array(array("day1"=>1,"day2"=>1,"name"=>"Ram"),array("day1"=>1,"day2"=>2,"name"=>"Raj"),array("day1"=>1,"day2"=>3,"name"=>"Rahul"),array("day1"=>2,"day2"=>3,"name"=>"Rocky"));
    $min = min(array_column($data, 'day1'));
    $max = max(array_column($data, 'day2'));
    $result = array_map(function($v) use($min, $max){$v['day1'] = $min; $v['day2'] = $max; return $v; }, $data);