找到最大的键值并从php中的多维数组返回其他键及其对应的值

时间:2019-06-10 09:55:42

标签: php arrays multidimensional-array

我有一个具有以下格式的多维数组。我正在尝试打印半径最大的数组。该函数应返回最大半径的详细信息。例如,对于Davis,它应返回半径为106(具有最大半径)的第二个内部数组,对于john,应返回半径为50的第二个内部数组。

我尝试使用此link中提供的解决方案。

Array
(
    [0] => Array
        (
            [name] => davis
            [data] => Array
                (
                    [0] => Array
                        (
                            [xaxis] => 445
                            [yaxis] => 447
                            [radius] => 80

                        )

                    [1] => Array
                        (
                            [xaxis] => 468
                            [yaxis] => 447
                            [radius] => 77

                        )

                    [2] => Array
                        (
                            [xaxis] => 409
                            [yaxis] => 199
                            [radius] => 106

                        )

                )

        )
       [1] => Array
        (
            [name] => john
            [data] => Array
                (
                    [0] => Array
                        (
                            [xaxis] => 311
                            [yaxis] => 383
                            [radius] => 50

                        )

                    [1] => Array
                        (
                            [xaxis] => 527
                            [yaxis] => 310
                            [radius] => 21

                        )

                    [2] => Array
                        (
                            [xaxis] => 465
                            [yaxis] => 431
                            [radius] => 48

                        )

                    [3] => Array
                        (
                            [xaxis] => 339
                            [yaxis] => 326
                            [radius] => 43

                        )

                )

        )

)

1 个答案:

答案 0 :(得分:2)

代码段,我认为半径是唯一的,否则它将重叠

$result = [];
foreach ($arr as $key => $value) {
    // it will map radius as key and whole array as its value
    $temp = array_column($value['data'], null, 'radius');
    // I am fetching max key by which I will fetch data in next step
    $key = max(array_keys($temp));
    // fetching data of max value and saving it for the name
    $result[$value['name']] = $temp[$key];
}
print_r($result);die;

Demo

如果您想保持数组结构原样,

$result = [];
$i      = 0;
foreach ($arr as $key => $value) {
    $temp               = array_column($value['data'], null, 'radius');
    $key                = max(array_keys($temp));
    $result[$i]['name'] = $value['name'];
    $result[$i]['data'] = $temp[$key];
    $i++;
}
print_r($result);die;

Demo