Given an array of arrays, how can I replace all empty values with 0?

末鹿安然 提交于 2020-01-05 05:30:10

问题


Example array

$myArray[0] = array('23', null, '43', '12');
$myArray[1] = array(null, null, '53', '19');
$myArray[2] = array('12', '13', '14', null);

All nulls should be replaced with 0. I was hoping someone would have an efficient way of doing this, perhaps a built in PHP function that I am unaware of.


回答1:


You could use the array_walk_recursive function, with a callback function that would replace null by 0.


For example, considering your array is declared this way :

$myArray[0] = array(23, null, 43, 12);
$myArray[1] = array(null, null, 53, 19);
$myArray[2] = array(12, 13, 14, null);

Note : I supposed you made a typo, and your arrays are not containing only a string, but several sub-elements.


You could use this kind of code :

array_walk_recursive($myArray, 'replacer');
var_dump($myArray);


With the following callback functon :

function replacer(& $item, $key) {
    if ($item === null) {
        $item = 0;
    }
}

Note that :

  • the first parameter is passed by reference !
    • which means modifying it will modify the corresponding value in your array
  • I'm using the === operator for the comparison


And you'd get the following output :

array
  0 => 
    array
      0 => int 23
      1 => int 0
      2 => int 43
      3 => int 12
  1 => 
    array
      0 => int 0
      1 => int 0
      2 => int 53
      3 => int 19
  2 => 
    array
      0 => int 12
      1 => int 13
      2 => int 14
      3 => int 0



回答2:


If the single quotation marks are unintentional, and the arrays have integers and null values:

for ($i = 0; $i < count($myArray); $i++)
{
    if ($myArray[$i] == null) $myArray[$i] = 0;
}


来源:https://stackoverflow.com/questions/2647959/given-an-array-of-arrays-how-can-i-replace-all-empty-values-with-0

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!