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条)

报告相同问题?

悬赏问题

  • ¥20 @microsoft/fetch-event-source 流式响应问题
  • ¥15 ogg dd trandata 报错
  • ¥15 高缺失率数据如何选择填充方式
  • ¥50 potsgresql15备份问题
  • ¥15 Mac系统vs code使用phpstudy如何配置debug来调试php
  • ¥15 目前主流的音乐软件,像网易云音乐,QQ音乐他们的前端和后台部分是用的什么技术实现的?求解!
  • ¥60 pb数据库修改与连接
  • ¥15 spss统计中二分类变量和有序变量的相关性分析可以用kendall相关分析吗?
  • ¥15 拟通过pc下指令到安卓系统,如果追求响应速度,尽可能无延迟,是不是用安卓模拟器会优于实体的安卓手机?如果是,可以快多少毫秒?
  • ¥20 神经网络Sequential name=sequential, built=False