多维数组提取相等的列值

Multidimensional array extract equal column values

我有以下数组

  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"
  }
}

因为您可以看到前 2 个元素具有相等的 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 功能实现吗?任何想法将不胜感激。

没有内置函数可以做到这一点。这是逻辑:

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

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

$newArray = array_values($newArray);

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