PHP array_merge empty values always less prioritar

▼魔方 西西 提交于 2019-12-23 09:31:08

问题


My goal is to merge 2 different arrays.

I have table "a" & "b". Data from table "a" are more prioritar.

PROBLEM: if a key from "a" contains an empty value, I would like to take the one from table "b".

Here is my code:

<?php

$a = array('key1'=> "key1 from prioritar", 'my_problem'=> "");

$b = array('key1'=> "key1 from LESS prioritar", 'key2'=>"key2 from LESS prioritar", 'my_problem'=> "I REACHED MY GOAL!");

$merge = array_merge($b, $a);

var_dump($merge);

Is there a way to do this in one function without doing something like below?

foreach($b as $key => $value)
{
  if(!array_key_exists($key, $a) || empty($a[$key]) ) {
    $a[$key] = $value;
  }
}

回答1:


You can use array_replace and array_filter

$mergedArray = array_replace($b, array_filter($a));

The result would be:

array(3) {
  ["key1"]=>
  string(19) "key1 from prioritar"
  ["key2"]=>
  string(24) "key2 from LESS prioritar"
  ["my_problem"]=>
  string(18) "I REACHED MY GOAL!"
}



回答2:


Just array_filter() $a which will remove any item with '' value.

$merge = array_merge($b, array_filter($a));


来源:https://stackoverflow.com/questions/34351102/php-array-merge-empty-values-always-less-prioritar

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