我有一个多维关联数组,其中包含一组数组。我想从某些数组值更改我的数组索引值。
我已经尝试过一些数组函数,但是我的数组还包含一些空数组,因此laravel函数keyBy不会给我想要的结果。
$arr1=array(0 =>array(),1=>array(0=>array('quan'=>10,'handle' => 'baroque'),1 =>array('quan'=>20,'handle' => 'baroque')),
2 =>array (0 =>array('quan' => 5,'handle' => 'adidas')));
我的预期结果数组必须是这样
$arr2=array(0 =>array(),'baroque'=>array(0=>array('quan'=>10,'handle' => 'baroque'),1 =>array('quan'=>20,'handle' => 'baroque')),
'adidas' =>array (0 =>array('quan' => 5,'handle' => 'adidas')));
答案 0 :(得分:0)
您可以使用经典的foreach
。使用isset
检查元素0的句柄是否存在,如果存在,请将其用作键。
$arr1 = //...
$result = array();
foreach($arr1 as $key => $val) {
if (is_array($val) && isset($val[0]["handle"])) $result[ $val[0]["handle"] ] = $val;
else $result[$key] = $val;
}
$result
将是:
Array
(
[0] => Array
(
)
[baroque] => Array
(
[0] => Array
(
[quan] => 10
[handle] => baroque
)
[1] => Array
(
[quan] => 20
[handle] => baroque
)
)
[adidas] => Array
(
[0] => Array
(
[quan] => 5
[handle] => adidas
)
)
)
答案 1 :(得分:0)
可以直接在handle
上作为键进行分组,而无条件使用。
$result = [];
foreach ($arr as $key => $value) {
if (!empty($value)) {
foreach ($value as $key1 => $value1) {
$result[$value1['handle']][] = $value1;
}
} else {
$result[] = $value;
}
}
输出:-
Array
(
[0] => Array
(
)
[baroque] => Array
(
[0] => Array
(
[quan] => 10
[handle] => baroque
)
[1] => Array
(
[quan] => 20
[handle] => baroque
)
)
[adidas] => Array
(
[0] => Array
(
[quan] => 5
[handle] => adidas
)
)
)
答案 2 :(得分:0)
尝试一下。
$res = [];
foreach($x as $key => $value)
{
if(empty($value))
{
$res[] = $value;
}
else
{
foreach($value as $v => $k)
{
if(array_key_exists($k['handle'],$res))
{
$res[$k['handle']][] = ['quan' => $k['quan'],'handle' => $k['handle']];
}
else
{
$res[$k['handle']][0] = ['quan' => $k['quan'],'handle' => $k['handle']];
}
}
}
}
结果将是这样。
Array
(
[0] => Array
(
)
[baroque] => Array
(
[0] => Array
(
[quan] => 10
[handle] => baroque
)
[1] => Array
(
[quan] => 20
[handle] => baroque
)
)
[adidas] => Array
(
[0] => Array
(
[quan] => 5
[handle] => adidas
)
)
)