php - 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:


In the above data set, the minimumday1 value is{-code-3} and the maximumday2 value is3. I need to apply those two values (respective to their column) to theday1 andday2 values in every rows.

Expected output:

    ["day1" => {-code-3}, "day2" => 3, "name" => "Ram"],
    ["day1" => {-code-3}, "day2" => 3, "name" => "Raj"],
    ["day1" => {-code-3}, "day2" => 3, "name" => "Rahul"],
    ["day1" => {-code-3}, "day2" => 3, "name" => "Rocky"]



This will help -

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





this will help: check the demo

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

People are also looking for solutions to the problem: php - Codeigniter email class not working


Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.