数组在PHP中的二维数组中是唯一的

时间:2010-03-25 21:12:06

标签: php arrays sorting multidimensional-array arraylist

嗨我有一个看起来像这样的数组:

Array ( [0] => Array ( [x] => 01 [y] => 244 ) [1] => Array ( [x] => 02 [y] => 244 ) [2] => Array ( [x] => 03 [y] => 244 ) [3] => Array ( [x] => 04 [y] => 243 ) [4] => Array ( [x] => 05 [y] => 243 ) [5] => Array ( [x] => 05 [y] => 244 ) [6] => Array ( [x] => 06 [y] => 242 ) [7] => Array ( [x] => 06 [y] => 243 ) [8] => Array ( [x] => 07 [y] => 243 ) [9] => Array ( [x] => 08 [y] => 243 ) [10] => Array ( [x] => 09 [y] => 242 ) [11] => Array ( [x] => 10 [y] => 244 ) [12] => Array ( [x] => 12 [y] => 243 ) [13] => Array ( [x] => 13 [y] => 243 ) [14] => Array ( [x] => 13 [y] => 243 ) [15] => Array ( [x] => 15 [y] => 243 ) ) 

x表示某个变量的天数和y值。我想显示一个独特的天数x(最后一个元素)和实际值。

例如第6天我有两个y值,但我想只显示最后一个(243)。

感谢您的帮助

1 个答案:

答案 0 :(得分:1)

这样做的一种方法就是使用一个简单的循环来生成一个新数组,在你继续的时候覆盖给定日期的任何现有值。

代码段

// $data = ... your array from the question
$result = array();
foreach ($data as $value) {
    $result[$value['x']] = $value['y'];
}

print_r($result);

<强>输出

Array
(
    [01] => 244
    [02] => 244
    [03] => 244
    [04] => 243
    [05] => 244
    [06] => 243
    [07] => 243
    [08] => 243
    [09] => 242
    [10] => 244
    [12] => 243
    [13] => 243
    [15] => 243
)

如果上述内容不适合您,则有许多替代方法(或主题的变体)。