Php 多维数组提取相等列值
我有以下数组Php 多维数组提取相等列值,php,arrays,element,Php,Arrays,Element,我有以下数组 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
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函数实现吗?如果您有任何想法,我们将不胜感激。没有内置功能可以做到这一点。这就是逻辑:
$initialArray = [/** your data **/];
$newArray = [];
foreach ($initialArray as $item) {
$newArray[$item['customer_id']][] = $item;
}
$newArray = array_values($newArray);
首先,创建一个由客户ID索引的新数组,该数组包含该客户的所有元素。然后(可选)如果希望对其进行数字索引,可以使用
array\u value
清除客户id数组索引。没有内置函数来精确执行此操作。这就是逻辑:
$initialArray = [/** your data **/];
$newArray = [];
foreach ($initialArray as $item) {
$newArray[$item['customer_id']][] = $item;
}
$newArray = array_values($newArray);
首先,创建一个由客户ID索引的新数组,该数组包含该客户的所有元素。然后(可选)如果希望对其进行数字索引,请使用
array\u value
清除客户id数组索引。我尝试过您的方案,但缺少一个元素。当我添加$tempCartsArray[$cart['customer_id']][$key]=$cart时,它就开始工作了;我看不出元素丢失的原因,请提供一些它不起作用的地方的例子。@RumenPanchev,这种方法在我看来是合理的。使用样本数据的var\u export
s编辑您的问题。()我尝试过你的场景,但缺少一个元素。当我添加$tempCartsArray[$cart['customer_id']][$key]=$cart时,它就开始工作了;我看不出元素丢失的原因,请提供一些它不起作用的地方的例子。@RumenPanchev,这种方法在我看来是合理的。使用样本数据的var\u export
s编辑您的问题。()可能的副本可能的副本