0

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

// 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);

任何想法?

4

2 回答 2

1

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

<?php 

$result = [];

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

print_r($result);
于 2021-05-22T05:46:09.950 回答
0

用于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
)
于 2021-05-26T09:06:04.133 回答