PHP:创建数组的数组,忽略空数组

发布于 2024-08-10 03:27:24 字数 384 浏览 12 评论 0原文

我需要创建一个数组的数组。
我一直在使用 array_map(null,$a,$b,$c) 来执行此操作并且它工作正常,但是,如果映射的数组之一不存在,则它不起作用。

为了解决这个问题,我使用了:

$myArray= array();
if (isset($a)) {
    array_push($myArray,$a);
}
if (isset($b)) {
    array_push($myArray,$b);
}
if (isset($c)) {
    array_push($myArray,$c);
}

是否有更优雅/更短的编写方法?
我尝试通过 array_map($function,$a,$b,$c) 应用一些函数,但没有成功。

I need to create an array of arrays.
I have been using array_map(null,$a,$b,$c) to do this and it works fine, however, it doesn't work if one of the mapped arrays doesn't exist.

To get around this problem I have used:

$myArray= array();
if (isset($a)) {
    array_push($myArray,$a);
}
if (isset($b)) {
    array_push($myArray,$b);
}
if (isset($c)) {
    array_push($myArray,$c);
}

Is there a more elegant/shorter method of writing this?
I've tried applying some functions via array_map($function,$a,$b,$c) but with no luck.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

对不⑦ 2024-08-17 03:27:25

您可以使用以下函数:

function joinArrays(){
  $arrays = func_get_args();
  $output = array();
  foreach($arrays as $array){
     if(!empty($array)) array_push($output, $array);
  }
  return $output;
}

调用如下: joinArrays($a, $b, $c, etc..);

You could use the following function:

function joinArrays(){
  $arrays = func_get_args();
  $output = array();
  foreach($arrays as $array){
     if(!empty($array)) array_push($output, $array);
  }
  return $output;
}

call like: joinArrays($a, $b, $c, etc..);

年华零落成诗 2024-08-17 03:27:24
$myArray = array_filter(array($a, $b, $c));
$myArray = array_filter(array($a, $b, $c));
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文