这是我的数组,但有些值是空数组,我想将它们转换为空字符串,但我不确定如何。尝试一些解决方案,但"无法将数组转换为字符串"。
array(1) {
[0]=>
array(32) {
["product_id"]=>
string(2) "30"
["name"]=>
string(12) "Canon EOS 5D"
["model"]=>
string(9) "Product 3"
["sku"]=>
array(0) {
}
["upc"]=>
array(0) {
}
["ean"]=>
array(0) {
}
["jan"]=>
array(0) {
}
["manufacturer_id"]=>
string(1) "9"
["tax_class_id"]=>
string(1) "9"
["points"]=>
string(1) "0"
["quantity"]=>
string(1) "7"
["minimum"]=>
string(1) "1"
["isbn"]=>
array(0) {
}
["mpn"]=>
array(0) {
}
["stock_status_id"]=>
string(1) "6"
}
但我想要这些:
["sku"]=>
array(0) {
}
["upc"]=>
array(0) {
}
["ean"]=>
array(0) {
}
["jan"]=>
array(0) {
}
看起来像这样:
["sku"]=>
string(0) ""
["upc"]=>
string(0) ""
["ean"]=>
string(0) ""
["jan"]=>
string(0) ""
a.k.a空字符串,而不是数组。就是这样。也许有些检查是否为空数组转换为字符串,我不确定。谢谢你!
答案 0 :(得分:1)
当值为空时,只需用空字符串替换它。
foreach($array as $k=>$v){
if(empty($v)){
$array[$k]='';
}
}
答案 1 :(得分:1)
使用array_map
。检查以下代码:
$array2 = array_map(function($value) {
return count($value) == 0 ? "" : $value;
}, $array);
答案 2 :(得分:1)
foreach ($products['shopproduct'] as $product) {
foreach ($product as $k => $v) {
if (empty($v)) {
$product[$k] = '';
}
}
}
echo "<pre>";
var_dump($products['shopproduct']);
您在foreach中使用数组副本($ product)的问题。 您可以使用&符号作为参考,如
foreach ($products['shopproduct'] as &$product) {
...
或
foreach ($products['shopproduct'] as $j => $product) {
foreach ($product as $k => $v) {
if (empty($v)) {
$products['shopproduct'][$j][$k] = '';
}
}
}