多维数组提取相等的列值

问题描述 投票:0回答:1

我有以下数组

  array(3) {
  [0]=>
  array(3) {
    ["cart_id"]=>
    string(6) "269984"
    ["customer_id"]=>
    string(5) "55152"
    ["product_id"]=>
    string(4) "2323"
  }
  [1]=>
  array(3) {
    ["cart_id"]=>
    string(6) "269985"
    ["customer_id"]=>
    string(5) "55152"
    ["product_id"]=>
    string(3) "730"
  }
  [2]=>
  array(3) {
    ["cart_id"]=>
    string(6) "269986"
    ["customer_id"]=>
    string(5) "66666"
    ["product_id"]=>
    string(4) "7297"
  }
}

如您所见,前两个元素具有相等的customer_id值。我想在一个新数组中提取所有相等或不相等的列值,它们看起来像这样:

  array(2) {
  [0]=>
  array(2) {
    [0]=>
    array(3) {
      ["cart_id"]=>
      int(269984)
      ["customer_id"]=>
      int(55152)
      ["product_id"]=>
      int(2323)
    }
    [1]=>
    array(3) {
      ["cart_id"]=>
      int(269985)
      ["customer_id"]=>
      int(55152)
      ["product_id"]=>
      int(730)
    }
  }
  [1]=>
  array(1) {
    [0]=>
    array(3) {
      ["cart_id"]=>
      int(269986)
      ["customer_id"]=>
      int(66666)
      ["product_id"]=>
      int(7297)
    }
  }
}

这可能通过一些PHP功能吗?任何想法,将不胜感激。

php arrays element
1个回答
2
投票

没有功能可以做到这一点。这是逻辑:

$initialArray = [/** your data  **/];
$newArray = [];

foreach ($initialArray as $item) {
    $newArray[$item['customer_id']][] = $item;
}

$newArray = array_values($newArray);

首先,您创建一个由客户ID索引的新数组,该客户ID包含该客户的所有元素。然后(可选)如果您希望对其进行数字索引,则使用array_values清除客户ID数组索引。

© www.soinside.com 2019 - 2024. All rights reserved.