PHP根据现有键值添加新的数组键

时间:2018-07-16 04:05:17

标签: php arrays

如何基于数组中的值向现有数组添加新的数组键和值?下面只是数组的一部分。原始的有大约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
 )

1 个答案:

答案 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