duanmianxue2687 2014-08-11 07:46
浏览 44
已采纳

如何根据PHP中的键值回显数组中的值

Please help me with this array printing.

Array

 [year_2014] => Array
    (
        [0] => Array
            (
                [amount] => 21960
                [year] => 2014
                [month] => 1
            )

        [1] => Array
            (
                [amount] => 25866
                [year] => 2014
                [month] => 2
            )

        [2] => Array
            (
                [amount] => 7840
                [year] => 2014
                [month] => 3
            )

        [3] => Array
            (
                [amount] => 424644
                [year] => 2014
                [month] => 5
            )

        [4] => Array
            (
                [amount] => 22052
                [year] => 2014
                [month] => 6
            )

        [5] => Array
            (
                [amount] => 28037
                [year] => 2014
                [month] => 7
            )

    )

I need to echo amount in according to month so the Output will be,

Result

  21960, 25866, 7840, 0, 424644, 22052, 28037, 0, 0, 0, 0, 0

Result eg.

That is if a month is not present then the value need to be zero,I need all the twelve month.

My dear Good Hearts please help me to get this result.

Some background

project is done in codeigniter , I have messed with some for, foreach but it's not working.

Thank you.

  • 写回答

6条回答 默认 最新

  • dongmouhao7438 2014-08-11 08:15
    关注

    Just try with:

    $output = array_fill(0, 12, 0);
    array_map(function ($item) use (&$output) {
        $output[$item['month'] - 1] = $item['amount'];
    }, $input['year_2014']);
    

    or with simple foreach:

    $output = array_fill(0, 12, 0);
    foreach ($input['year_2014'] as $item) {
        $output[$item['month'] - 1] = $item['amount'];
    }
    

    Output:

    array (size=12)
      0 => int 21960
      1 => int 25866
      2 => int 7840
      3 => int 0
      4 => int 424644
      5 => int 22052
      6 => int 28037
      7 => int 0
      8 => int 0
      9 => int 0
      10 => int 0
      11 => int 0
    

    Explanation:

    array_fill creates an array with 12 elements filled with 0 values.

    foreach loops over year_2014 data arrays and sets item's amounts to the month - 1 position.

    array_map does the same as foreach and can be an overkill here, but also works well.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(5条)

报告相同问题?

悬赏问题

  • ¥50 导入文件到网吧的电脑并且在重启之后不会被恢复
  • ¥15 (希望可以解决问题)ma和mb文件无法正常打开,打开后是空白,但是有正常内存占用,但可以在打开Maya应用程序后打开场景ma和mb格式。
  • ¥20 ML307A在使用AT命令连接EMQX平台的MQTT时被拒绝
  • ¥20 腾讯企业邮箱邮件可以恢复么
  • ¥15 有人知道怎么将自己的迁移策略布到edgecloudsim上使用吗?
  • ¥15 错误 LNK2001 无法解析的外部符号
  • ¥50 安装pyaudiokits失败
  • ¥15 计组这些题应该咋做呀
  • ¥60 更换迈创SOL6M4AE卡的时候,驱动要重新装才能使用,怎么解决?
  • ¥15 让node服务器有自动加载文件的功能