我有以下要编辑的数组:
Array
(
[qty_black_34] =>
[qty_black_36] => 2
[qty_black_38] =>
[qty_black_40] =>
[qty_black_42] =>
[qty_black_44] =>
[qty_black_48] =>
[qty_powder_34] =>
[qty_powder_36] =>
[qty_powder_38] =>
[qty_powder_40] =>
[qty_powder_42] => 1
[qty_powder_44] =>
[qty_powder_48] =>
[qty_red_34] =>
[qty_red_36] =>
[qty_red_38] => 2
[qty_red_40] =>
[qty_red_42] =>
[qty_red_44] =>
[qty_red_48] => )
我想要做的是构建另一个数组以仅保存带有值的元素。 新数组必须看起来像这样“
Array
(
[0] => Array
(
[color] => black
[size] => 36
[quantity] => 2
)
[1] => Array
(
[color] => powder
[size] => 42
[quantity] => 1
)
[2] => Array
(
[color] => red
[size] => 38
[quantity] => 2
)
)
PHP是我正在使用的语言。
答案 0 :(得分:4)
循环遍历数组并获取已设置值的元素。对于最终数组中的其他键/值,将用作原始数组中的键的字符串拆分为
$new_array = array();
foreach ($old_array as $key => value) {
if ($value) {
$key_split = explode('_', $key);
$new_array[] = array('color' => $key_split[1], 'size' => $key_split[2], 'quantity' => $value);
}
}
答案 1 :(得分:1)
$products = array();
foreach($quantities as $key => $quantity){
if($quantity != '') {
list($q, $color, $size) = explode('_', $key);
$products[] = array(
'color' => $color,
'size' => $size,
'quantity' => $quantity
);
}
}