将项插入特定索引

时间:2016-07-25 23:30:00

标签: php arrays

我有一个索引数组。我处理数组中的项目并将处理后的项目推送到新的关联数组中。在进行中,我遗漏了一些项目。我处理稍后遗漏的项目,现在我需要将这些项目添加到新数组中,但我希望它们的位置与原始数组相同。

由于第一个数组已编入索引而第二个数组是关联的,因此这有点棘手。

检查以下代码:

$array1 = [
    "item 1a",
    "item 2k",
    "item 3special",
    "item 4f",
    "item 5v",
];

// process $array1, leave out the special item
// create $array2 with the processed items

$array2 = [
    "a" => "item 1a",
    "k" => "item 2k",
    "f" => "item 4f",
    "v" => "item 5v",
];

// process the special item
// insert the special item into $array2 using its original position in $array1
// ???

期望的输出:

$array2 = [
    "a" => "item 1a",
    "k" => "item 2k",
    "s" => "item 3 processed",
    "f" => "item 4f",
    "v" => "item 5v",
];

我通过创建第三个数组,保存数组的原始位置,循环第二个数组,跟踪索引等来解决了这个问题。见下文:

$special_item = "item 3special";
$si_processed = "oh, I am so special";
$org_position = array_search($special_item, $array1); // 2

$new_array = [];

$index = 0;
foreach ($array2 as $key => $value) {
    if ($index == $org_position) {
        $array3["s"] = $si_processed;
    }
    $array3[$key] = $value;
    $index++;
}
print_r($array3);

输出:

Array
(
    [a] => item 1a
    [k] => item 2k
    [s] => oh, I am so special
    [f] => item 4f
    [v] => item 5v
)

有没有更好的方法来解决这个问题,也许是一个我不知道的PHP函数?

更新:使用How to insert element into arrays at specific position?答案中的代码,我将这个功能整合在一起:

function insertAt($array = [], $item = [], $position = 0) {
    $previous_items = array_slice($array, 0, $position, true);
    $next_items     = array_slice($array, $position, NULL, true);
    return $previous_items + $item + $next_items;
}

$org_position = array_search($special_item, $array1); // 2
$array2       = insertAt($array2, ["s" => $si_processed], $org_position);

0 个答案:

没有答案