猿问

如何关联和过滤两个相关的数组?

我有两个数组,我想在处理它们时将它们链接在一起。


$dat = array(

    "2020-02-01", 

    "2020-02-05",

    "2020-02-10",

    "2020-02-12",

    "2020-02-15"

);

$word = array(

    "Attend To,Explore,Unaided,dull,bad"

); 


//User input

$start = "2020-01-01";

$end = "2020-02-07";

我希望输入也影响第二个数组,所以当第一个数组从第一个 2 获得结果时,第二个数组也应该从第一个 2 获得结果。


//Filter out dates between start and end date

$result = array_filter($dat, function($data_item) use($start, $end) {

    return $data_item >= $start && $data_item <= $end;

});

结果是


Array

(

    [0] => 2020-02-01

    [1] => 2020-02-05

)

我希望它能够链接$dat,$word这样 word 的结果也将是


Array

(

    [0] => Attend To

    [1] => Explore

)


慕尼黑8549860
浏览 108回答 3
3回答

慕哥9229398

对于这种情况,我认为函数式编程不是非常可读/有吸引力。只需使用一个简单的 foreach 循环并有条件地获取与共享索引相关的单词。由于这两个数组共享公共索引,因此无需对这combine两个数组进行操作——只需引用索引即可。代码:(演示)$dat = ["2020-02-01", "2020-02-05", "2020-02-10", "20-02-12", "2020-02-15"];$word = ["Attend To,Explore,Unaided,dull,bad"];$words = explode(',', $word[0]);//User input$start = "2020-01-01";$end = "2020-02-07";$result = [];foreach ($dat as $index => $date) {&nbsp; &nbsp; if ($date >= $start && $date <= $end) {&nbsp; &nbsp; &nbsp; &nbsp; $result[] = $words[$index];&nbsp; &nbsp; }}var_export($result);输出:array (&nbsp; 0 => 'Attend To',&nbsp; 1 => 'Explore',)

手掌心

之后将保留原始密钥array_filter,因此通过计算交集来获取相同密钥的条目。看起来这$word是一个带有字符串的单元素数组,所以只需分解它:$word_result = array_intersect_key(explode(',', $word[0]), $result);查看演示。如果其中一个数组具有唯一值,您可以组合该数组并对其进行操作。$comb = array_combine(explode(',', $word[0]), $dat);$result = array_filter($comb, function($data_item) use($start,$end) {&nbsp; &nbsp; return $data_item >= $start && $data_item <= $end;});这产生:Array(&nbsp; &nbsp; [Attend To] => 2020-02-01&nbsp; &nbsp; [Explore] => 2020-02-05)您可以按原样使用数组,也可以array_keys将键用作数组$word。如果不能保证是,$word[0]那么您可以使用reset($word)or current($word)。

呼如林

假设数组具有相同的键(我更改它以反映这一点)的可能解决方案是使用常量ARRAY_FILTER_USE_BOTHto array_filter,以便该键在回调函数中可用。$result2在这里,我在过滤数据时用单词填充第二个数组(请注意,添加的东西use是$result2通过引用传递的):$dat = array("2020-02-01","2020-02-05","2020-02-10","20-02-12","2020-02-15");$word = array("Attend To","Explore","Unaided","dull","bad");&nbsp;//User input$start = "2020-01-01";$end = "2020-02-07";//Filter out dates between start and end date$result2 = [];$result = array_filter($dat, function($data_item, $key) use($start, $end, $word, &$result2) {&nbsp; &nbsp; if($data_item >= $start && $data_item <= $end){&nbsp; &nbsp; &nbsp; &nbsp; $result2[$key] = $word[$key];&nbsp; &nbsp; &nbsp; &nbsp; return true;&nbsp; &nbsp; }&nbsp; &nbsp; return false;}, ARRAY_FILTER_USE_BOTH);当只需要过滤时,AbraCadaver 的答案非常适合,但如果有人必须在过滤器回调中执行额外操作,这可能很有用。
随时随地看视频慕课网APP
我要回答