drrkgbm6851 2018-05-05 16:25
浏览 5
已采纳

PHP - 确保数组包含特定键

I have a PHP array like this..

Array
(
    [04] => 1
    [09] => 1
    [10] => 1
    [01] => 1
)

I want to make sure that it has keys 1-10 in it, if they do not exist then I want them to be added with a value of 0, so my final array looks like this..

Array
(
    [01] => 1
    [02] => 0
    [03] => 0
    [04] => 1
    [05] => 0
    [06] => 0
    [07] => 0
    [08] => 0
    [09] => 1
    [10] => 1
)

I am doing it like this..

if (!array_key_exists("01",$myarray)) {
     $myarray['01'] = 0;
}

if (!array_key_exists("02",$myarray)) {
     $myarray['02'] = 0;
}

if (!array_key_exists("02",$myarray)) {
     $myarray['02'] = 0;
}

if (!array_key_exists("03",$myarray)) {
     $myarray['03'] = 0;
}

And so on up until 10, then I do a ksort to get them in the right order

ksort($myarray)

This works but I am aware this is quite clunky and probably not very efficient.

Can anyone point me towards a better solution?

  • 写回答

6条回答 默认 最新

  • dongxin2734 2018-11-16 23:33
    关注

    Using functional techniques ends up making your process look convoluted. An important factor in choosing the right solution should be the omission of the ksort() call. If a coding solution is engineered properly, you store the data in the desired order to begin with -- no mopping up after iterating.

    Code: (Demo)

    $data = ["04" => 1, "09" => 1, "10" => 1, "01" => 1];
    
    for ($x = 1; $x < 11; ++$x) {
        $key = sprintf("%02d", $x);  // ensure proper padding with 0
        $result[$key] = $data[$key] ?? 0;  // null coalescing operator from php5.6+
    }
    
    print_r($result);
    

    Output:

    Array
    (
        [01] => 1
        [02] => 0
        [03] => 0
        [04] => 1
        [05] => 0
        [06] => 0
        [07] => 0
        [08] => 0
        [09] => 1
        [10] => 1
    )
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(5条)

报告相同问题?

悬赏问题

  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度