使用foreach为同一个键添加更多值

时间:2017-05-15 09:08:28

标签: php foreach

所以我有这样的数组:

[
    (int) 0 => [
        'user_id' => (int) 20098238,
        'location_id' => (int) 20014727
    ],
    (int) 1 => [
        'user_id' => (int) 20098238,
        'location_id' => (int) 20027167
    ],
    (int) 2 => [
        'user_id' => (int) 20098238,
        'location_id' => (int) 20027168
    ],
    (int) 3 => [
        'user_id' => (int) 20098238,
        'location_id' => (int) 20027169
    ],
    (int) 4 => [
        'user_id' => (int) 20011189,
        'location_id' => (int) 20012490
    ],
    (int) 5 => [
        'user_id' => (int) 20011189,
        'location_id' => (int) 20016161
    ],
    (int) 6 => [
        'user_id' => (int) 20011189,
        'location_id' => (int) 20018679
    ],
    (int) 7 => [
        'user_id' => (int) 20011189,
        'location_id' => (int) 20023569
    ],
    (int) 8 => [
        'user_id' => (int) 20102015,
        'location_id' => (int) 20008315
    ],
    (int) 9 => [
        'user_id' => (int) 20102015,
        'location_id' => (int) 20008689
    ],
    (int) 10 => [
        'user_id' => (int) 20102015,
        'location_id' => (int) 20021267
    ]
]

我想把它作为像这样的restult数组

[
    (int) 20098238 => [
        (int) 0 => (int) 20014727,
        (int) 1 => (int) 20027167,
        (int) 2 => (int) 20027168,
        (int) 3 => (int) 20027169

    ],
    (int) 20011189 => [
        (int) 0 => (int) 20012490,
        (int) 1 => (int) 20016161,
        (int) 2 => (int) 20018679,
        (int) 3 => (int) 20023569

    ],
    (int) 20102015 => [
        (int) 0 => (int) 20008315,
        (int) 1 => (int) 20008689,
        (int) 2 => (int) 20021267
    ]
]

这是我的代码,但我只获得了排序的一部分

$customerData = [];
foreach ($userIds as $data) {
  $i = 0;
  foreach ($customerData as $k => $check) {
    if ($k == $data['user_id']) {
      $customerData[$k][$i] = $data['location_id'];
    }
    $i++;
  }
  $customerData[$data['user_id']][$i] = $data['location_id'];
}

结果这个代码生成像user_id这样的密钥,但推送该密钥的数组存在问题。我每个键的位置总是最多2个。

感谢您的帮助!

2 个答案:

答案 0 :(得分:1)

您的完美解决方案就在这里:

$customerData = [];
    foreach ($userIds as $data) {

      foreach ($customerData as $k => $check) {
        if ($k == $data['user_id'] && $data['location_id'] == $check) {
          $customerData[$k][] = $data['location_id'];
        }

      }
      $customerData[$data['user_id']][] = $data['location_id'];
    }

Live Demo

答案 1 :(得分:0)

只需删除$i用法并在循环中使用$customerData[$k][]即可。这将自动为userid数组添加一个新的出现次数。

$customerData = [];

foreach ($userIds as $data) {

    foreach ($customerData as $k => $check) {
        $customerData[$k][] = $data['location_id'];
    }

}