简体   繁体   中英

Apply column min and column max to every row in a 2d array

I need to find the minimum value in one column and the maximum value in another column of a two-dimensional array and apply those values to every row in the array.

Sample input:

$array = [
    ["day1" => 1, "day2" => 1, "name" => "Ram"],
    ["day1" => 1, "day2" => 2, "name" => "Raj"],
    ["day1" => 1, "day2" => 3, "name" => "Rahul"],
    ["day1" => 2, "day2" => 3, "name" => "Rocky"]
];

In the above data set, the minimum day1 value is 1 and the maximum day2 value is 3 . I need to apply those two values (respective to their column) to the day1 and day2 values in every rows.

Expected output:

[
    ["day1" => 1, "day2" => 3, "name" => "Ram"],
    ["day1" => 1, "day2" => 3, "name" => "Raj"],
    ["day1" => 1, "day2" => 3, "name" => "Rahul"],
    ["day1" => 1, "day2" => 3, "name" => "Rocky"]
]

This will help -

$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);

Output

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

this will help: check the 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);

Instead of using multiple cycles ( foreach() loops and or array_column() calls), this task can be completed in 1 cycle by declaring reference variables at all elements which need to be updated with the min/max values.

Below, the final iteration's $day1 and $day2 values will be distributed to all points of reference.

Code: ( Demo )

foreach ($array as &$row) {
    $day1 = min($day1 ?? $row['day1'], $row['day1']);
    $day2 = max($day2 ?? $row['day2'], $row['day2']);
    $row['day1'] = &$day1;
    $row['day2'] = &$day2;
}
var_export($array);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM