重叠的关联数组

时间:2013-06-21 18:34:48

标签: php arrays associative-array

我需要重叠来自多个关联数组的数据,并考虑以下因素:

  • 如果存在匹配的密钥,则覆盖它
  • 如果某个键存在但不匹配,请将新值附加到该元素
  • 如果以上都不是,请创建一个元素来存储值

以下列结构为例:

 <?php

 for ($i = 0; $i < 10; $i++) {
    $table["table_$i"] = array(
        "cell_0" => array(
        'row'     => 12,
        'column'  => 5
        )
    );
 }

 for ($i = 4; $i < 12; $i++) {
    $table["table_$i"] = array(
        "cell_0" => array(
        'row'     => 9,
        'column'  => 8
        )
    );
 }

 for ($i = 5; $i < 15; $i++) {
    $table["table_$i"] = array(
        "cell_1" => array(
        'row'     => 4,
        'column'  => 1
        )
    );
 }

 ?>

所需的输出如下所示:

 {"table_0":{"cell_0":{"row":12,"column":5}},"table_1":{"cell_0":{"row":12,"column":5}},"table_2":{"cell_0":{"row":12,"column":5}},"table_3":{"cell_0":{"row":12,"column":5}},"table_4":{"cell_0":{"row":9,"column":8}},"table_5":{"cell_0":{"row":9,"column":8},"cell_1":{"row":4,"column":1}},"table_6":{"cell_0":{"row":9,"column":8},"cell_1":{"row":4,"column":1}},"table_7":{"cell_1":{"row":4,"column":1}},"table_8":{"cell_0":{"row":9,"column":8},"cell_1":{"row":4,"column":1}},"table_9":{"cell_0":{"row":9,"column":8},"cell_1":{"row":4,"column":1}},"table_10":{"cell_0":{"row":9,"column":8},"cell_1":{"row":4,"column":1}},"table_11":{"cell_0":{"row":9,"column":8},"cell_1":{"row":4,"column":1}},"table_12":{"cell_1":{"row":4,"column":1}},"table_13":{"cell_1":{"row":4,"column":1}},"table_14":{"cell_1":{"row":4,"column":1}}}

从所需的输出中注意,cell_0的值不会替换cell_1的值:在这种情况下,我无法使用array_merge()获得所需的输出。

任何帮助将不胜感激 - 谢谢!

1 个答案:

答案 0 :(得分:1)

检查array_mergearray_unique php函数。