我在mysql中有两行和这些查询:
SELECT * FROM `fruits_colors` WHERE `name` = "default"
SELECT * FROM `fruits_colors` WHERE `name` = "example"
我得到了:
//result from first query
$default_row = array(
'banana' => 'yellow',
'apple' => 'red',
'grape' => 'green',
'blueberry' => 'blue'
'raspberry' => 'red'
);
//result from second query
$example_row = array(
'banana' => 'yellow',
'apple' => 'GREEN',
'grape' => '',
'blueberry' => 'blue'
'raspberry' => ''
);
所以,现在我想用$ example_row中的所有空值填充默认值($ default_row),但不要替换那些非空的值。所以我应该得到:
$example_row = array(
'banana' => 'yellow',
'apple' => 'GREEN', // keep original from this array
'grape' => 'green', // filled from $default_row
'blueberry' => 'blue'
'raspberry' => 'red'// filled from $default_row
);
我知道我可以使用$ example_row创建foreach,检查每个键,如果value为空,则使用其他数组中的值设置。但是,还有更优雅的简短方法吗?
此致
答案 0 :(得分:1)
尝试这个解决方案。
$return = array();
foreach($example_row as $k => $v) {
if(empty($v) || ($v == "")) {
$return[$key] = $default_row[$key];
} else {
$return[$key] = $v;
}
}
var_dump($return);
答案 1 :(得分:1)
您可以尝试这样的事情:
SELECT COALESCE(NULLIF(`name`,''), SELECT `name` FROM fruits_colors
WHERE `name` = "default")
FROM fruits_colors
WHERE `name` = "example"