【问题标题】:Array Check if key not exist add default value数组检查键是否不存在添加默认值
【发布时间】:2020-12-05 18:37:54
【问题描述】:
$list = Array
    (
        [Jul] => Array
            (
                [deposit] => Array
                    (
                        [totalcount] => 1
                        [totalamount] => 12
                    )
    
            )
    
        [Oct] => Array
            (
            )
    
        [Nov] => Array
            (
            )
    
        [Dec] => Array
            (
                [deposit] => Array
                    (
                        [totalcount] => 2
                        [totalamount] => 2400
                    )
    
                [withdraw] => Array
                    (
                        [totalcount] => 1
                        [totalamount] => 3000
                    )
    
            )
 
    )

//我的代码

foreach ($list as $ekey => $evalue) {
            if(!array_column($list[$ekey], 'deposit')){
                $list[$ekey]['deposit'] = array(
                                        'totalcount'  => 0,
                                        'totalamount' => 0
                                    );
            }else if(!array_column($list[$ekey], 'withdraw')){
                $list[$ekey]['withdraw'] = array(
                                        'totalcount'  => 0,
                                        'totalamount' => 0
                                    );
            }
        }

问题:上面的代码是检查每个数组里面的数据是否有相同的key,是不是表示数组中的每个key都应该有"deposit"“撤回”。如果未找到,它将为其分配默认值。但是我的代码只会将存款值插入那些丢失的值,它不会将提现值插入其中?任何人都可以帮助解决这个问题:(??

【问题讨论】:

  • 在第 7 行使用 if 而不是 else if
  • 扩展@Lessmore 的评论,elseif 分支只有在第一个条件不满足时才会进入。因此,您的代码没有涵盖depositwithdraw 都丢失的情况。由于这些是独立的,因此您需要两个独立的条件。

标签: php arrays


【解决方案1】:

将现有值合并到默认值会更容易:

$default = array('deposit'  => array('totalcount'  => 0, 'totalamount' => 0),
                 'withdraw' => array('totalcount'  => 0, 'totalamount' => 0));

foreach ($list as &$evalue) {
    $evalue = array_merge($default, $evalue);
}

【讨论】:

    【解决方案2】:

    此选项使用原始列表中的键和空值创建一个模板数组。然后它使用array_replace_recursive() 将开始列表中的任何现有值覆盖到模板数组中......

    $template = array_fill_keys(array_keys($list), [
            "deposit" => ["totalcount" => 0,"totalamount" => 0],
            "withdraw" => ["totalcount" => 0,"totalamount" => 0]
    ]);
    $list = array_replace_recursive($template, $list);
    

    【讨论】:

      猜你喜欢
      • 2018-10-10
      • 2021-07-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-05-03
      • 1970-01-01
      • 1970-01-01
      • 2019-04-23
      相关资源
      最近更新 更多