Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/283.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/arrays/14.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
PHP统一重复数组_Php_Arrays - Fatal编程技术网

PHP统一重复数组

PHP统一重复数组,php,arrays,Php,Arrays,在我的PHP代码中,我有许多这样的数组: 0 = ['attr_id':1,'name':'qty','value':'100']; 1 = ['attr_id':1,'name':'qty','value':'200']; 2 = ['attr_id':1,'name':'qty','value':'500']; 3 = ['attr_id':2,'name':'price','value':'10$']; 0 = ['attr_id':1,'name':'qty','value':['10

在我的PHP代码中,我有许多这样的数组:

0 = ['attr_id':1,'name':'qty','value':'100'];
1 = ['attr_id':1,'name':'qty','value':'200'];
2 = ['attr_id':1,'name':'qty','value':'500'];
3 = ['attr_id':2,'name':'price','value':'10$'];
0 = ['attr_id':1,'name':'qty','value':['100','200','500']];
1 = ['attr_id':1,'name':'price','value':'10$'];
我希望按如下方式合并此阵列:

0 = ['attr_id':1,'name':'qty','value':'100'];
1 = ['attr_id':1,'name':'qty','value':'200'];
2 = ['attr_id':1,'name':'qty','value':'500'];
3 = ['attr_id':2,'name':'price','value':'10$'];
0 = ['attr_id':1,'name':'qty','value':['100','200','500']];
1 = ['attr_id':1,'name':'price','value':'10$'];
你们能帮帮我吗?
这是一种方法,您可以在id的数组和列数组中循环,并使用键插入值数组中的值

$value = array_column($arr, 'value');
$id = array_column($arr, 'attr_id');
$res =[];

Foreach($id as $key => $i){
    If(!isset($res[$i])) $res[$i] = ['attr_id' => $i, 'name'=>'qty', 'value' => []];
    $res[$i]['value'][] = $value[$key];
}
Var_dump($res);

如您所见,我使用id作为键来跟踪结果数组。
如果要清除此项,即从0重置计数,请使用数组_值

$res = array_values($res);
编辑:在我的回答中,10美元也在一个数组中,这使我以后更容易使用数组。

如果必须将其另存为字符串,我可以修复它,但以后将数组与混合项一起使用可能会更困难。

这应该更简单。使用
attr\u id
作为索引构建结果,并附加

foreach($array as $values) {
    $result[$values['attr_id']]['value'][] = $values['value'];
    $result[$values['attr_id']] = $result[$values['attr_id']] + $values;
}

如果需要重新索引,只需在
$result
上使用
array\u values()

attr\u id':1
?打字错误你试过循环或其他什么吗?你放弃了吗?@Abracadver不,你的解决方案对我有用。谢谢:)