我正在尝试创建一个新的数组($names),它的大小与$years数组相同。我正在循环遍历$year变量,但是很难将$years_names变量加倍(首先用逗号,然后用冒号),但不确定这是最好的方法。也正因为如此,我无法使用search_array。由于它可能没有每年的数据,所以我希望新的数组在该年的位置上保留一个空值。所以在我的$years_names变量中,我缺少了2010年到2012年的数据,所以索引0-1应该为空,索引8,因为2018年也没有数据。附件或多或少是我试图为我的$names数组获取的东西。谢谢!

$years = range(2010, 2020);
$data_years = "2010,2011,2012,2013,2014,2015,2016,2017,2018,2019,2020";
$data_names = "Charlie,Lucy,Linus,Pig Pen,Snoopy,Woodstock,Peppermint Patty,Marcie";
$years_names = "2012:Charlie,2013:Lucy,2014:Linus,2015:Pig Pen,2016:Snoopy,2017:Woodstock,2019:Peppermint Patty,2020:Marcie";
$Exploded = explode(',', $years_names);
$names = [];
foreach($Exploded as $i => $item) {
$names[$i] = explode(':', $item);
//echo "i= {$i}<br/>";
//echo "item= {$item}<br/>";
//echo $names[$i][0] . ':' . $names[$i][1] . "<br/>";
}发布于 2020-10-20 19:39:52
你可以做这样的事
$years = range(2010, 2020);
$years_names = "2012:Charlie,2013:Lucy,2014:Linus,2015:Pig Pen,2016:Snoopy,2017:Woodstock,2019:Peppermint Patty,2020:Marcie";
//split `$years_names` at comma
$split_values = explode(',', $years_names);
//convert values to a more usable format
$split_values = array_reduce($split_values, function($return, $item) {
//explode $item (e.g `2012:Charlie`) at the colon symbol
$explode = explode(':', $item);
//separate year from name as key => value
$return[$explode[0]] = $explode[1];
//this return reduces the current iteration of `$split_values` to the key=>value pair
return $return;
});
$names = [];
foreach($years as $year) {
//set default value as null. If year is not found in next loop, this will remain
$names[$year] = null;
//check if year exists in $split_values
if(array_key_exists($year, $split_values)) {
//if it does, set $names[$year] to that value
$names[$year] = $split_values[$year];
}
}
print_r($names);输出
Array
(
[2010] =>
[2011] =>
[2012] => Charlie
[2013] => Lucy
[2014] => Linus
[2015] => Pig Pen
[2016] => Snoopy
[2017] => Woodstock
[2018] =>
[2019] => Peppermint Patty
[2020] => Marcie
)https://stackoverflow.com/questions/64451921
复制相似问题