PHP数组排序数据

PHP数组排序数据

问题描述:

How can i get best way to get cheapest price from this php code ?

Array
    (
        [SKU0001901] => Array
            (
                [0] => 300000
                [1] => 50000
            )

        [SKU0001902] => Array
            (
                [0] => 400
                [1] => 2000000
                [2] => 500
            )

        [SKU0001903] => Array
            (
                [0] => 100000
                [1] => 500000
            )

    )

Expect : SKU0001901 is 50000 , SKU0001902 cheapest is 400, etc.

SOLVED

There many ways to answer my question. In my case, i use array_map.

$o = array_map('min', $array);

In the future, i want to make a research which method to make it faster, especially in big array data.

Just map min to your array:

$o = array_map('min', $array);

Here's a demo

This will work in your case.

$array_full= array( array('SKU0001901' =>  array(300000,50000),'SKU0001902' => array(400,2000000,500),'SKU0001903' =>  array(100000,500000)));
foreach($array_full[0] as $key=>$aaa){
    echo $key.' : '.min($aaa).'<br>';
}

You can use min to get lowest from array

Pretty simple, you can use foreach and sort.

Read more about the different array sorting methods here.

Use sort($v) in the foreach loop which sorts lowest to highest and does not preserve key indexes, so the 0th item in this array will always be the smallest value.

<?php
$input =  [
  'SKU0001901' => [
    300000,
    50000,
  ],
  'SKU0001902' => [
    400,
    2000000,
    500,
  ],
  'SKU0001903' => [
    100000,
    500000,
  ]
];

$output = [];
foreach ($input as $k => $v) {
  sort($v);
  $output[$k] = $v[0];
}
print_r($output);

Produces:

Array
(
    [SKU0001901] => 50000
    [SKU0001902] => 400
    [SKU0001903] => 100000
)

Simplest one with array_map and sort

Try this code snippet here

<?php
$array= array( 
        'SKU0001901' =>  array(300000,50000),
        'SKU0001902' => array(400,2000000,500),
        'SKU0001903' =>  array(100000,500000));
$array=array_map(function($value){
    sort($value,SORT_NUMERIC);
    return $value[0];
}, $array);
print_r($array);

Output:

Array
(
    [SKU0001901] => 50000
    [SKU0001902] => 400
    [SKU0001903] => 100000
)