在同一个键

时间:2016-10-31 15:48:28

标签: php arrays

我有两个阵列

118 => array:7 [
    "date" => "19.10.2016"
    "time1" => "dfg"
    "purpose1" => "dfg"
    "chair1" => "dfg"
    "time2" => "dfg"
    "purpose2" => "dfg5"
    "chair2" => "5345"
  ]
  123 => array:7 [
    "date" => "20.10.2016"
    "time1" => "gdf"
    "purpose1" => "gdfg"
    "chair1" => "gdf"
    "time2" => "gdfg"
    "purpose2" => "gdf"
    "chair2" => "534534"
  ]
  124 => array:7 [
    "date" => "20.10.2016"
    "time1" => "gdf"
    "purpose1" => "gdfg"
    "chair1" => "gdf"
    "time2" => "gdfg"
    "purpose2" => "gdf"
    "chair2" => "534534"
  ]

0 => {#231
    +"label_id": "D101102E"
    +"id": 118
  }
  1 => {#232
    +"label_id": "D1011100"
    +"id": 123
  }
  2 => {#233
    +"label_id": "D1011100"
    +"id": 124
  }

其中id是第一个数组中的键,第二个数组中是值。我希望将第一个数组中的label_id添加为与键相同的id中的值。我已经尝试使用array_fill_keys和array_push,但它不是重点。谢谢

1 个答案:

答案 0 :(得分:1)

迭代第一个数组,然后在嵌套循环中,迭代第二个数组,将外键与内部id进行比较。如果匹配,则将值附加到外部数组并继续下一个项目。

<?php

$a = [
    118 => [
        "date" => "19.10.2016",
        "time1" => "dfg",
        "purpose1" => "dfg",
        "chair1" => "dfg",
        "time2" => "dfg",
        "purpose2" => "dfg5",
        "chair2" => "5345",
    ],
    123 => [
        "date" => "20.10.2016",
        "time1" => "gdf",
        "purpose1" => "gdfg",
        "chair1" => "gdf",
        "time2" => "gdfg",
        "purpose2" => "gdf",
        "chair2" => "534534",
    ],
    124 => [
        "date" => "20.10.2016",
        "time1" => "gdf",
        "purpose1" => "gdfg",
        "chair1" => "gdf",
        "time2" => "gdfg",
        "purpose2" => "gdf",
        "chair2" => "534534",
    ],
];

$b = [
    0 => [
        "label_id" => "D101102E",
        "id" => 118,
    ],
    1 => [
        "label_id" => "D1011100",
        "id" => 123,
    ],
    2 => [
        "label_id" => "D1011100",
        "id" => 124,
    ],
];

foreach($a as $key => $value){
    foreach($b as $k => $v){
        if($key === $v['id']){
            $a[$key]['label_id'] = $k;
            continue;
        }
    }
}

print_r($a);
Array
(
    [118] => Array
        (
            [date] => 19.10.2016
            [time1] => dfg
            [purpose1] => dfg
            [chair1] => dfg
            [time2] => dfg
            [purpose2] => dfg5
            [chair2] => 5345
            [label_id] => 0
        )

    [123] => Array
        (
            [date] => 20.10.2016
            [time1] => gdf
            [purpose1] => gdfg
            [chair1] => gdf
            [time2] => gdfg
            [purpose2] => gdf
            [chair2] => 534534
            [label_id] => 1
        )

    [124] => Array
        (
            [date] => 20.10.2016
            [time1] => gdf
            [purpose1] => gdfg
            [chair1] => gdf
            [time2] => gdfg
            [purpose2] => gdf
            [chair2] => 534534
            [label_id] => 2
        )

)