如何基于数组中的值向现有数组添加新的数组键和值?下面只是数组的一部分。原始的有大约1000多个按键。
键Date
将始终存在。 Date
之前的值不是固定的,并且会更改。
这是我拥有的数组:
Array (
[0] => Date
[1] => Name
[2] => Other Data
[3] => More Data
[4] => Date
[5] => Name
[7] => Other Data
[8] => Date
[9] => Name
[10] => Other Data
)
除了第一个键,我想在数组中的每个Date
之前添加一个新键。这怎么可能?
Array (
[0] => Date
[1] => Name
[2] => Other Data
[3] => More Data
[*] => // New data here
[4] => Date
[5] => Name
[7] => Other Data
[*] => // New data here
[8] => Date
[9] => Name
[10] => Other Data
)
答案 0 :(得分:0)
尝试一下,它的工作原理。
<?php
$array1 = array('Date','Name','Other Data','More Data','Date','Name','Other Data','Date','Name','Other Data');
$array2 = array();
foreach($array1 as $k => $v) {
if($k != 0 && $array1[$k] == "Date") {
$array2['d'.($k+1)] = " // New Date";
}
$array2[] = $v;
}
?>
结果
Array
(
[0] => Date
[1] => Name
[2] => Other Data
[3] => More Data
[d5] => // New Date
[4] => Date
[5] => Name
[6] => Other Data
[d8] => // New Date
[7] => Date
[8] => Name
[9] => Other Data
)
您可以根据需要更改键或值。
"d1" as new key
"// New Date" as new value