Forum Moderators: coopster

Message Too Old, No Replies

Filtering/deleting elements in array

         

Lupi

9:22 pm on Jul 16, 2008 (gmt 0)

10+ Year Member



Hi,

in PHP, I have a twodimensional array like so:

[A][4x1][...][10][...]
[A][4x1][...][11][...]
[A][4x1][...][13][...]
[A][4x2][...][5][...]
[A][4x2][...][6][...]
[b][4x1][...][7][...]
[b][4x1][...][8][...]
[b][4x2][...][11][...]
[b][4x2][...][12][...]

I want to filter this array. Do you see how there's three subarrays where [0]=A and [1]=4x1, but different values in field [3]? I only want to keep one of those subarrays, the one with the lowest value in field[3]. Same for all the other subarrays where field [0] and [1] are the same.

Thus, this is the result I'm after.

[A][4x1][...][10][...]
[A][4x2][...][5][...]
[b][4x1][...][7][...]
[b][4x2][...][11][...]

I don't know what to do, I thought array_filter might work, but couldn't come up with the proper callback function.

I hope you can help me with this.

Cheers, Chris

MattAU

10:49 pm on Jul 16, 2008 (gmt 0)

10+ Year Member



I don't think array filter would help. What you need to do is create a sorting function that removes the unneeded values. Here's some basic code to do it:

function my_sort($old_array)
{
$sorted_array = array();

foreach($old_array as $level_0_key => $level_0_value)
{
foreach($level_0_value as $level_1_key => $level_1_value)
{
if(!isset($sorted_array[$level_0_key][$level_1_key]))
{
// This level_0 / level_1 combo doesn't yet exist in the sorted_array, so just add the current sub array
$sorted_array[$level_0_key][$level_1_key] = $level_1_value;
}
else
{
// This combo does exist in the sorted_array, check whether the key in field 3 is lower or not. If it's lower, replace the existing one with the new one
if(get_key_3($level_1_value) < get_key_3($sorted_array[$level_0_key][$level_1_key]))
{
// It's lower, replace with new value
$sorted_array[$level_0_key][$level_1_key] = $level_1_value;
}
}
return $sorted_array;
}

function get_key_3($level_1_array)
{
foreach($level_1_array as $level_2_key => $level_2_value)
{
foreach($level_2_value as $level_3_key => $level_3_value)
{
return $level_3_key;
}
}
}

That's it. It's quite early so I might've made a couple of mistakes, but you get the drift... There's also no error checking in which may be a problem if the array isn't formed perfectly.

HTH