[英]combine 2 comma separated list into one in php
I have 2 arrays that are coming from the database, [options]
column has comma-separated values.我有 2 个来自数据库的 arrays,
[options]
列有逗号分隔的值。
Array
(
[0] => Array
(
[id] => 143
[menu_id] => 590
[name] => bread
[options] => small, large
)
[1] => Array
(
[id] => 144
[menu_id] => 590
[name] => jam
[options] => mango, orange, grape
)
)
Is there have any way to combine the list of [options]
at [0]
and [1]
?有没有办法在
[0]
和[1]
处组合[options]
列表?
Example : small, large, mango, orange, grape
示例:
small, large, mango, orange, grape
Approach方法
<?php foreach ($menu_options as $key => $menu_option) : ?>
<?PHP $exploded_variant_options = explode(',', $menu_option['options']);
foreach ($exploded_variant_options as $exploded_variant_option) : ?>
<?php echo ucfirst(sanitize($exploded_variant_option)); ?> //print one by one
<?php endforeach; ?>
<?php endforeach; ?>
My suggestion would be to use array_merge
.我的建议是使用
array_merge
。 The code would look like this:代码如下所示:
<?php
$all_options = [];
foreach( $menu_options as $key => $menu_option ) {
$all_options = array_merge($all_options, explode(", ", $menu_option["options"]));
}
?>
if this is your array:如果这是你的数组:
$arrays = array (
array( 'id' => 143, 'menu_id' => 590, 'name' => 'bread', 'options' => 'small,large'),
array( 'id' => 144, 'menu_id' => 590, 'name' => 'jam', 'options' => 'mango,orange,grape')
);
you can use array_map for achieving that:您可以使用 array_map 来实现:
function spliter($key, $value){
if($key == 'options')
return $value = explode(',', $value);
else
return $value;
}
foreach($arrays as &$array)
$array = array_map( 'spliter' , array_keys($array), $array);
then this will be a dump of your $arrays
:那么这将是您的
$arrays
的转储:
array(2) {
[0]=>
array(4) {
[0]=>
int(143)
[1]=>
int(590)
[2]=>
string(5) "bread"
[3]=>
array(2) {
[0]=>
string(5) "small"
[1]=>
string(5) "large"
}
}
[1]=>
&array(4) {
[0]=>
int(144)
[1]=>
int(590)
[2]=>
string(3) "jam"
[3]=>
array(3) {
[0]=>
string(5) "mango"
[1]=>
string(6) "orange"
[2]=>
string(5) "grape"
}
}
}
If you just want to print out all the options (insertion order) and not modify them further, you could also just call this:如果您只想打印出所有选项(插入顺序)而不进一步修改它们,您也可以这样调用:
<?php
$arr = [
['id' => 143, 'menu_id' => 590, 'name' => 'bread', 'options' => 'small, large'],
['id' => 144, 'menu_id' => 590, 'name' => 'jam', 'options' => 'mango, orange, grape']
];
var_dump(array_reduce(array_column($arr, 'options'), function ($c, $i) {
return $c ? "${c}, ${i}" : $i;
}));
// prints: string(34) "small, large, mango, orange, grape"
?>
Otherwise, I suggest using the approach shown by "Teodor".否则,我建议使用“Teodor”所示的方法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.