简体   繁体   English

使用有序日期表达式数组来填充一个新数组,其中包含第二个数组中的数据,该数组由其数字键关联

[英]Use an array of ordered date expressions to populate a new array with data from a second array related by its numeric keys

I am not great with arrays, but I have to build a new array from two arrays, the new array has to use the order of the first array but the data of the second but in the same order of the first.我对 arrays 不是很好,但我必须从两个 arrays 构建一个新数组,新数组必须使用第一个数组的顺序,但第二个的数据但与第一个的顺序相同。

The first array and order:第一个数组和顺序:

$forecastedMonths = array(
    "May 22",
    "Jun 22",
    "Jul 22",
    "Aug 22",
    "Sep 22",
    "Oct 22",
    "Nov 22",
    "Dec 22",
    "Jan 23",
    "Feb 23",
    "Mar 23",
    "Apr 23"
);

And the second array I need to use the values of the second, but the keys in this represent the month.而第二个数组我需要使用第二个的值,但是其中的键代表月份。

Array
(
    [1] => 0
    [2] => 0
    [3] => 0
    [4] => 0
    [5] => 172427.89 //May
    [6] => 0
    [7] => 243730.79 //Jul
    [8] => 0
    [9] => 0
    [10] => 0
    [11] => 0
    [12] => 0
)

So the desired outcome would be所以期望的结果是

Array
(
    [0] => 172427.89
    [1] => 0
    [2] => 243730.79
    [3] => 0
    [4] => 0
    [5] => 0
    [6] => 0
    [7] => 0
    [8] => 0
    [9] => 0
    [10] => 0
    [11] => 0
)

Use array_map() to map the numeric data to the month-year expression.使用array_map()将 map 数字数据转换为月-年表达式。 To relate the data's numeric keys to the date expressions, use a datetime class plus a convert method, or just call date(strtotime()) .要将数据的数字键与日期表达式相关联,请使用日期时间 class 和转换方法,或者只调用date(strtotime())

Code: ( Demo ) ( Classic loop )代码:(演示)(经典循环

var_export(
    array_map(
        fn($My) => $data[date('n', strtotime($My))],
        $forecastedMonths
    )
);

Very relevant page: In PHP given a month string such as "November" how can I return 11 without using a 12 part switch statement?非常相关的页面:在 PHP 中给定月份字符串,例如“November”,如何在不使用 12 部分 switch 语句的情况下返回 11?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM