我有一个数组如下
Array
(
[0] => Array
(
[0] => Pedigree Dry
[1] => N/A
[2] => N/A
[3] => N/A
)
[1] => Array
(
[0] => Professional Range
[1] => N/A
[2] => N/A
[3] => N/A
)
[2] => Array
(
[0] => Pedigree Wet
[1] => N/A
[2] => N/A
[3] => N/A
)
[3] => Array
(
[0] => PMM
[1] => N/A
[2] => N/A
[3] => N/A
)
[4] => Array
(
[0] => Chappi
[1] => N/A
[2] => N/A
[3] => N/A
)
[5] => Array
(
[0] => Care & Treat
[1] => N/A
[2] => N/A
[3] => N/A
)
[6] => Array
(
[0] => Sheba
[1] => N/A
[2] => N/A
[3] => N/A
)
[7] => Array
(
[0] => Whiskas Dry
[1] => N/A
[2] => N/A
[3] => N/A
)
[8] => Array
(
[0] => Whiskas Wet
[1] => N/A
[2] => N/A
[3] => N/A
)
)
上面的代码是一个多维数组。但是所有数组元素(索引除外)都是N / A.我想用0替换所有N / A. 如何将所有N / A替换为0?
答案 0 :(得分:2)
$newArray = array();
foreach($array as $inner_array) {
$newArray[] = str_replace("N/A", 0, $inner_array);
}
循环遍历所有内部数组并用零替换所有“N / A”并将它们添加到新的结果数组中。
工作Demo
答案 1 :(得分:1)
试试这个:
function replaceNa($var) {
if ($var == 'N/A' ) {
return 0;
} else {
return $var;
}
}
$array = array(
array('Pedigre dry', 'N/A', 'N/A', 'N/A'),
array('Professional Range', 'N/A', 'N/A', 'N/A'),
array('Pedigree Wet', 'N/A', 'N/A', 'N/A'),
array('PMM', 'N/A', 'N/A', 'N/A'),
);
foreach ($array as $key => $item) {
$array[$key] = array_map('replaceNa', $item);
}
var_dump ($array);
答案 2 :(得分:-1)
我确信这里有一个比这更好的答案..但你总是可以做嵌套的foreach方法。
//loop through each Array (first level)
foreach ($arrays as $array)
{
//create two variables for each sub array so you have access to keys and values
foreach ($array as $key=>$value)
{
if ($value = "N/A")
{
$value = 0;
}
}
}