1

I have an array with the following data, I am trying to find the column with the lowest price and then get the associated row data (stock and supplier) value, I have managed to get the lowest price but am not sure how to get the associated row data for stock and supplier, any adivce. Thanks

$productdata=array
(
    array('Price'=>$row['price1'],'Stock'=>$row['stock1'],'Supplier'=>$row['supplier1']),
    array('Price'=>$row['price2'],'Stock'=>$row['stock2'],'Supplier'=>$row['supplier2']),
    array('Price'=>$row['price3'],'Stock'=>$row['stock3'],'Supplier'=>$row['supplier3'])
    );
$filtered_array = array_filter($productdata, function($v) {
return $v['Price'];});

$minprice= min( array_column( $filtered_array, 'Price') );
 print_r($minprice); 

3 Answers 3

3

A solution without using sorting or loops:

Get all the prices in an array, then get the key of the lowest price

$prices = array_column($productdata, 'Price');
$min_price = min($prices);
$key = array_search($min_price, $prices);

Output the matching row:

$match = $productdata[$key];
echo '<pre>' . print_r($match, true) . '</pre>';

Documentation:

Sign up to request clarification or add additional context in comments.

Comments

1

First sort your array in ascending order then you will get first element as lowest.

$filtered_array=array
(
    array('Price'=>100,'Stock'=>1000,'Supplier'=>'Kapil'),
    array('Price'=>50,'Stock'=>500,'Supplier'=>'Kapil2'),
    array('Price'=>200,'Stock'=>2000,'Supplier'=>'Kapil3')
    );

 for($i = 0; $i < count($filtered_array); $i++ ) {
    for($j = $i+1; $j< count($filtered_array); $j++ ) {

        if($filtered_array[$i]['Price'] > $filtered_array[$j]['Price']) {
            $temp = $filtered_array[$j];
            $filtered_array[$j] = $filtered_array[$i];
            $filtered_array[$i] = $temp;
        }
    }
 }
 print_r($filtered_array[0]);

Comments

0

You could sort the array by price in ascending order using usort. The array with to lowest price will then be the first item $productdata[0]

usort($productdata, function($a, $b) {
    return $a['Price'] > $b['Price'];
});

echo $productdata[0]["Stock"];

Example

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.