[英]Combine php array with matching index sets
I have two arrays $arrayOne, $arrayTwo 我有两个数组$ arrayOne,$ arrayTwo
$arrayOne = Array (
[0] => 2012-01-30
[1] => 1999-04-20
)
$arrayTwo = Array (
[0] => new
[1] => old
)
I want to merge the arrays by data index's and give the key name so the result should go. 我想通过数据索引合并数组并给出键名,这样结果就可以了。 something like 就像是
$new = Array (
[0] =>
"Date" => 2012-01-30
"Condition" => New
[1] =>
"Date" => 1999-04-20
"Condition" => Old
)
I have tried 我努力了
$newArray = array_merge($arrayOne, $arrayTwo)
just to combine the arrays, but this is not the format i was looking for 只是为了组合数组,但这不是我想要的格式
Assuming the arrays always match in length, this will work: 假设数组的长度始终匹配,这将起作用:
$newArray = array();
foreach( $arrayOne as $i => $val )
{
$newArray[] = array(
'Date' => $val,
'Condition' => ucfirst($arrayTwo[$i])
);
}
You could also do it this way: 您也可以这样进行:
<?php
$dates = [
"2012-01-30",
"1999-04-20"
];
$ages = [
"new",
"old"
];
$results = array_map(function($date, $age) {
return [ "Date" => $date, "Condition" => $age ];
}, $dates, $ages);
Produces: 产生:
Array
(
[0] => Array
(
[Date] => 2012-01-30
[Condition] => new
)
[1] => Array
(
[Date] => 1999-04-20
[Condition] => old
)
)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.