Jump to content

Sorting & Editing a Multidimensional Array


wpt394

Recommended Posts

Greetings all.  I'm trying to figure out a way to sort and edit a multidimensional array.  For example, suppose I have a list of fruits and their corresponding prices in this multidimensional array...

 

$MyArray = Array(

Array('apple','20'),
Array('banana','15'),
Array('orange','35'),
Array('apple', '15'),
Array('orange', '26'),
Array('pear', '22'),
Array('banana', '13'),
Array('banana', '40')

);

 

My goal is to extract the lowest cost entry of each fruit.  So, given the example, in the end, I would like to have a new array that would be something like,

 

$newArray = Array(

Array('apple', '15'),
Array('banana', '15'),
Array('orange', '26'),
Array('pear', '22'),

);

 

My first thought was to do something such as sorting $MyArray by the price values in ascending order, and then possibly using the in_array() function in a loop to write $newArray.  The problem is, I don't know how to implement in_array() with multidimensional arrays.  Any suggestions?  Or is there perhaps a more elegant way to accomplish this altogheter?  Thanks in advance for any help offered.

Link to comment
https://forums.phpfreaks.com/topic/58605-sorting-editing-a-multidimensional-array/
Share on other sites

Why make it a multi Dimensional array?

 

<?php
$fruit_array = array("apple" => 20, "banana" => 15); // ....etc
?>

 

Than you can sort it by the key (which is alphabetical) or by the value (which is numeric) using the regular www.php.net/sort functions.

You really have to re-arrange your data before you can do anything with it. I came up with:

 

<?php 
$myarray = Array(

Array('apple','20'),
Array('banana','15'),
Array('orange','35'),
Array('apple', '15'),
Array('orange', '26'),
Array('pear', '22'),
Array('banana', '13'),
Array('banana', '40')

);
$items = array();
foreach($myarray as $key => $value){//rearrange array into a more useful form. We have an array containing an array of each of the prices for a given item
$items["$value[0]"][] = $value[1];
}
foreach($items as $key => $value){//cycle through each item. Sort the prices
sort($value);
echo "The cheapest $key costs $value[0]<br />";
}
?> 

 

 

Thanks Frost110, but suppose there are more than two elements in each sub-array.  Suppose it was something like...

 

$myArray = Array(

Array('apple','20','source1'),
Array('banana','22','source1'),
Array('pear','28','source2'),
Array('apple',33','source2'),
Array('banana','15','source2')

);

 

Then what would be the best route to take?

It depends.

 

I would do a different array structure

 

<?php
// this is structured for items
$fruity = array(0 => array("name" => "apple", "price" => 20, "source" => 1), 1 => array("name" => "orange", "price" => 15, "source" => 2));

// a different approach
$fruity = array("apple" => array("name" => "apple", "price" => 20, "source" => 1), "orange" => array("name" => "orange", "price" => 15, "source" => 2));
?>

 

As to sorting them, I would check the user comments for the sort features. If not the way I would do it is loop through the array and specify an index name in a function and put all those into their own array with the appropriate index. Sort by that and than restructure a new array by that.

try

<?php
$myArray = Array(
Array('apple','20','source1'),
Array('banana','22','source1'),
Array('pear','28','source2'),
Array('apple','33','source2'),
Array('banana','15','source2'));

$tmp = array();
$out = array();

foreach ($myArray as $v) if (!array_key_exists($v[0],$tmp) or $v[1] < $tmp[$v[0]][1]) $tmp[$v[0]] = $v;
foreach ($tmp as $v) $out[] = $v; 

print_r($out);
?>

Sort the array first by fruit,price then loop through the array printing first price for each item

<?php
$MyArray = Array(

Array('apple', 20),
Array('banana',15),
Array('orange',35),
Array('apple', 15),
Array('orange', 26),
Array('pear', 22),
Array('banana', 13),
Array('banana', 40)

);

function mysort($a, $b)
{
    if ($a[0] == $b[0])
    {
         if ($a[1] == $b[1]) return 0;
         return ($a[1] < $b[1]) ? -1 : 1;
    }
    return ($a[0] < $b[0]) ? -1 : 1;
}


usort ($MyArray, 'mysort');

$prev = '';
foreach ($MyArray as $f)
{
    if ($f[0] != $prev)
    {
        echo "$f[0] $f[1]<br>";
        $prev = $f[0];
    }
}

?>

 

~GingerRobot, before you ask ;)

 

GingerRobot time 0.038582

Barand time 0.000204

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.