简体   繁体   中英

How To Find 2 Minimum Numbers Row and Column From Array Multidimensional in PHP

I have a multidimensional array in PHP like below

$tabel = array(
             array(8,10,9),
             array(10,8,3)
         );

and I want to find the 2 minimum numbers by row and column from that array.

Before it I only have to calculate from no array multidimensional, the code like below

<?php
    $baris1 = array(8,16,20,10,10);
    $n1 = $n2 = 1000 ; 
    $m1 = $m2 = -1 ;
    for ($i = 0 ; $i < count($array); $i++) {
            $x = $array[$i] ;      
            if ($x <= $n1){
                $n2 = $n1 ;            
                $n1 = $x ;
            } elseif ($x < $n2){
                $n2 = $x;
            }
    }
    echo "Min Number = $n1 $n2<br>";

A simple way to do it is to merge them all together into one array.

$all = array_merge(...$tabel);

// or for PHP < 5.6
// $all = call_user_func_array('array_merge', $tabel);

Then you can sort that and take the first two values.

sort($all);
$min_two = array_slice($all, 0, 2);

For your input example where $tabel = [[8,10,9], [10,8,3]]; , the result would be [3, 8] .

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