简体   繁体   English

php 数组 select 元素依赖于其他数组

[英]php array select element depended on other array

i have an array for weeks days like this我有一个像这样的几周的数组

$daysNumber=array(1,2,3,4,5,6,7);

I need to convert it to names like this我需要把它转换成这样的名字

$daysName = array('sunday', 'monday', 'tuesday', 'wednesday', 'thursday', 'friday','saturday');

the days numbers it's dynamic the user selects them and i get the array for example like this (1,3,4) i want to replace each number with the day name like this (Sunday,Tuesday,wednesday)天数是动态的

what is the best option to convert it转换它的最佳选择是什么

You can drop the $daysNumber variable and start the $daysName at 1 rather than 0.您可以删除$daysNumber变量并将$daysName从 1 而不是 0 开始。

You can then use array_key_intersect() and array_flip() to extract the days you are after...然后你可以使用array_key_intersect()array_flip()来提取你之后的日子......

$daysName = array( 1=> 'sunday', 'monday', 'tuesday', 'wednesday', 'thursday', 'friday','saturday');

$selected = [1,3,4];

print_r(array_intersect_key($daysName, array_flip($selected)));

gives...给...

Array
(
    [1] => sunday
    [3] => tuesday
    [4] => wednesday
)

Your array $daysName is enough:您的数组$daysName就足够了:

$daysName = array('sunday', 'monday', 'tuesday', 'wednesday', 'thursday', 'friday','saturday');

As it is zero-indexed, its indexes correspond to your $daysNumber as index - 1 .由于它是零索引的,因此它的索引对应于您的$daysNumber作为index - 1

So for 1,3,4 you output:所以对于1,3,4你 output:

$daysName[0];  // 1 - 1
$daysName[2];  // 3 - 1
$daysName[3];  // 4 - 1

But if you still need you can reindex your $daysName starting from 1:但是,如果您仍然需要,您可以从 1 开始重新索引您的$daysName

$daysName = array(1 => 'sunday', 2 => 'monday', 3 => 'tuesday'); // etc

You can try date with array_map您可以使用array_map尝试date

$alphaDays = array_map(function($d){
    $d--;
    return date('l', strtotime("Sunday + $d Days"));
}, $days);
print_r($alphaDays);

Working example:- https://3v4l.org/aCDRh工作示例:- https://3v4l.org/aCDRh

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

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