doushu0591 2016-05-20 18:02
浏览 70
已采纳

从给定数组的公共第一个索引值中查找数组中的值并对其进行分组

Suppose I have this multidimensional array:

Array(

[0] => Array
    (
        [0] => 08/Mar/2004
        [1] => apple
    )

[1] => Array
    (
        [0] => 08/Mar/2004
        [1] => orange
    )

[2] => Array
    (
        [0] => 09/Mar/2004
        [1] => mango
    )

[3] => Array
    (
        [0] => 09/Mar/2004
        [1] => grape
    )

[4] => Array
    (
        [0] => 10/Mar/2004
        [1] => apple
    )

[5] => Array
    (
        [0] => 10/Mar/2004
        [1] => kiwi
    )
)

The dates present in the array are unknown, meaning that the array can have other date such as 11/Mar/2004 and 12/Mar/2004 and so on at each first position of the sub array.

An array should be dynamically created for every different date present.

I want to retrieve all the value at index 1 from the sub arrays for all the common dates and save the values in the newly created array for the corresponding date.

I want the result to be as follows:

Array(
    [0] => 08/Mar/2004
    [1] => apple
    [2] => orange
)

Array(
    [0] => 09/Mar/2004
    [1] => mango
    [2] => grape
)

Array(
    [0] => 10/Mar/2004
    [1] => apple
    [2] => kiwi
)

Any help would be much appreciated.

  • 写回答

1条回答 默认 最新

  • donglang1894 2016-05-20 18:10
    关注

    This should do it:

    foreach($array as $value)  {
        if(!isset($result[$value[0]])) {
            $result[$value[0]][] = $value[0];
        }
        $result[$value[0]][] = $value[1];
    }
    
    $result = array_values($result);
    

    Loop the array and build a result array:

    • If the result with date as key does not exist then create it and add the date
    • Then append the fruit
    • Finally, re-index if needed
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥50 如何用脚本实现输入法的热键设置
  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能
  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀
  • ¥20 手写数字识别运行c仿真时,程序报错错误代码sim211-100
  • ¥15 关于#hadoop#的问题
  • ¥15 (标签-Python|关键词-socket)