doupao5296 2017-08-08 08:02
浏览 58
已采纳

PHP - 仅当值不为null时才设置数组键

Is there a shorter solution for something like this?

$manufacturer = array();

if(!is_null($params->get('name'))){
    $manufacturer['name'] = $params->get('name');
}

if(!is_null($params->get('link'))){
    $manufacturer['link'] = $params->get('link');
}

if(!is_null($params->get('description'))){
    $manufacturer['description'] = $params->get('description');
}

...

So a key of an array should only be set with the value if the value is not null. This is a bit shorter, but with this solution the keys will exist with the value NULL. But they should not even exist when the value was NULL:

$manufacturer = array(
    'name' => !is_null($params->get('name')) ? $params->get('name') : null,
    'link' => !is_null($params->get('link')) ? $params->get('link') : null,
     'description' => !is_null($params->get('description')) ? $params->get('description') : null
);

EDIT:

It should work for multidimensional arrays and the array keys and param keys may vary

  • 写回答

3条回答 默认 最新

  • dtzhfb4869 2017-08-08 09:03
    关注

    for @u_mulder foreach and @Nono array_filter solutions they work only for simple array, they do not remove null values from multidimensional arrays,

    try this recursive function:

    <?php
    /**
     just keep your array like this:
    
    $manufacturer = array(
        'name' => $params->get('name'),
        'link' => $params->get('link'),
        'description' => $params->get('description'),
        'attribute' => array (
            'street' => $params->get('street'),
            ...
        )
        ...
    );
    **/
    
    $manufacturer = [
        'name' => 'yoeunes',
        'link' => null,
        'description' => 'fake description',
        'attribute' => [
            'street' => null,
            'city'   => 'Marrakech',
        ],
    ];
    
    function array_remove_null($array)
    {
        foreach ($array as $key => $value) {
            if (is_array($value)) {
                $array[$key] = array_remove_null($array[$key]);
            }
    
            if (is_null($array[$key])) {
                unset($array[$key]);
            }
        }
    
        return $array;
    }
    
    echo "<pre>";
    print_r(array_remove_null($manufacturer));
    

    output:

    Array
    (
        [name] => yoeunes
        [description] => fake description
        [attribute] => Array
            (
                [city] => Marrakech
            )
    
    )
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 R语言卸载之后无法重装,显示电脑存在下载某些较大二进制文件行为,怎么办
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?
  • ¥15 关于#vue.js#的问题:修改用户信息功能图片无法回显,数据库中只存了一张图片(相关搜索:字符串)
  • ¥15 texstudio的问题,
  • ¥15 spaceclaim模型变灰色