【问题标题】:PHP array_combine if not nullPHP array_combine 如果不为空
【发布时间】:2021-05-22 05:31:50
【问题描述】:

我只想在值存在的情况下合并数据。示例:

// array 1
array:4 [▼
  0 => "qwfd"
  1 => "qw2e3"
  2 => null
  3 => null
]
// array 2
array:4 [▼
  0 => "qwef"
  1 => "w2"
  2 => null
  3 => null
]

我需要忽略两个数组中的2=>3=>,因为它们都是空的。

Ps即使其中一个为null也需要忽略(示例)

// array 1
array:4 [▼
  0 => "qwfd"
  1 => "qw2e3"
  2 => "i am here"
  3 => null
]
// array 2
array:4 [▼
  0 => "qwef"
  1 => "w2"
  2 => null
  3 => null
]

在这种情况下,数组12=> 具有值,但因为数组22=> 没有。也不应该合并。

My code

$names = $request->input('social_media_name'); // array 1
$usernames = $request->input('social_media_username'); // array 2
$newArray = array_combine($names, $usernames);

有什么想法吗?

【问题讨论】:

    标签: php arrays array-combine


    【解决方案1】:

    这很简单。循环并检查索引处的值是否为空。如果其中任何一个是,则跳过它,否则设置键值对。

    <?php 
    
    $result = [];
    
    foreach($names as $index => $val){
      if (is_null($val) || is_null($usernames[ $index ]) continue;
      $result[ $val ] = $usernames[ $index ];
    }
    
    print_r($result);
    

    【讨论】:

      【解决方案2】:

      使用array_filter 过滤出仅当$name, $username 不为空时才返回的数组。或者即使其中一个为 null 也不返回。

      $names = [0 => "qwfd",1 => "qw2e3",2 => "i am here",3 => null];
      $usernames = [0 => "qwef",1 => "w2",2 => null,3 => null];
      
      $newArray = array_combine($names, $usernames);
      $newArray = array_filter($newArray,
                    fn($name, $username)=>!is_null($name) and
                           !is_null($username),ARRAY_FILTER_USE_BOTH);
      
      echo '<pre>'; print_r($newArray);
      

      打印:

      Array
      (
          [qwfd] => qwef
          [qw2e3] => w2
      )
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-06-29
        • 1970-01-01
        • 1970-01-01
        • 2021-11-07
        • 1970-01-01
        相关资源
        最近更新 更多