PHP - 如果缺少值,则保存数组

时间:2016-08-18 10:38:10

标签: php arrays

我想在数组中保存两个数组。 此示例有效

    $myArray = [];
    $a = [1,2,3,4];
    $b = [1,2,3,4];

输出

Array
(
 [a] => Array
   (
   [0] => 1
   [1] => 2
   [2] => 3
   )
 [b] => Array
   (
   [1] => 11
   [2] => 22
   [3] => 33
 )
)

我的问题是在数组中,缺少一个值然后出现错误

Array
(
 [a] => Array
  (
   [0] => 1
   [1] => 2
   [2] => 3
  )
 [b] => Array
  (
   [1] => 11
   [2] => 
   [3] => 33
  )
)

我需要像这样的输出。如果缺少值

Array
(
 [a] => Array
  (
   [0] => 1
   [2] => 3
  )
   [b] => Array
  (
   [1] => 11
   [3] => 33
  )
)

我该怎么办? 谢谢。

2 个答案:

答案 0 :(得分:0)

php中有一个函数:array_filter将删除数组中等于false(==)的所有项。您可以使此函数适用于递归工作,因此它也将从子数组中删除所有空值。

该方法应如下所示:

function array_filter_recursive($input) 
  { 
    foreach ($input as &$value) 
    { 
      if (is_array($value)) 
      { 
        $value = array_filter_recursive($value); 
      } 
    } 

    return array_filter($input); 
  } 

要获得没有空值的新数组,请按以下方式调用:

 $myArray = array_filter_recursive($myArray); //Or pass the array name where you have the data.

答案 1 :(得分:0)

给这个功能一个......

function removeBlankElements(array & $firstArray, array & $secondArray)
{
    // Search for null, '', or false values in $secondArray
    $secondArrayRemovalIndexes = array_unique(array_merge(array_keys($secondArray, null), array_keys($secondArray, ''), array_keys($secondArray, false)));
    $firstArrayRemoveIndexes = [];
    // Build up an array of index in the $firstArray for the blank values found in the $secondArray
    foreach ($secondArrayRemovalIndexes as $secondIndex) {
        $firstIndex = array_search($secondIndex, $firstArray);
        if ($firstIndex !== false) {
            $firstArrayRemoveIndexes[] = $firstIndex;
        }
    }
    // Remove the indexes we have built up.
    $firstArray = array_diff_key($firstArray, array_flip($firstArrayRemoveIndexes));
    $secondArray = array_diff_key($secondArray, array_flip($secondArrayRemovalIndexes));
}

然后在实践中它看起来像这样:

// Here's the demo array you have
$x = [
    'a' => [
        0 => 1,
        1 => 2,
        2 => 3,
    ],
    'b' => [
        1 => 11,
        2 => null,
        3 => 33,
    ],
];
// Run the function passing in our 2 arrays
removeBlankElements($x['a'], $x['b']);

结果......

var_dump($x);

array(2) {
    'a' =>
  array(2) {
        [0] =>
    int(1)
    [2] =>
    int(3)
  }
  'b' =>
  array(2) {
        [1] =>
    int(11)
    [3] =>
    int(33)
  }
}