具有多维数组的array_splice中断插入的数组

时间:2018-07-13 12:04:26

标签: php

我具有以下数组结构:

$tpl = [
    'breadcrumbs' => [
        [ 'title' => 'Item Database', 'text' => 'Item Database', 'url' => SITE_DOMAIN.ADMIN_PATH.'/items/' ],
        [ 'title' => $category->name, 'text' => $category->name, 'active' => true ]
    ]
];

我正尝试在最后一个元素之前插入元素,因此我可以按如下方式使用array_splice

if( !is_null($category->category) )
{
    array_splice(
        $tpl['breadcrumbs'],
        1,
        0,
        [ 'title' => $category->category->name, 'text' => $category->category->name, 'url' => SITE_DOMAIN.ADMIN_PATH.'/items/' ]
    );
}

但是,这似乎使我尝试插入的项目变平(根据预期的行为)并产生以下输出:

Array
(
    [0] => Array
        (
            [title] => Item Database
            [text] => Item Database
            [url] => https://local/qmdepot/admin/items/
        )

    [1] => Medical Department
    [2] => Medical Department
    [3] => https://local/qmdepot/admin/items/
    [4] => Array
        (
            [title] => Class 1
            [text] => Class 1
            [active] => 1
        )

)

预期输出应为:

Array
(
    [0] => Array
        (
            [title] => Item Database
            [text] => Item Database
            [url] => https://local/qmdepot/admin/items/
        )
    [1] => Array
        (
            [title] => Medical Department
            [text] => Medical Department
            [url] => https://local/qmdepot/admin/items/
        )
    [2] => Array
        (
            [title] => Class 1
            [text] => Class 1
            [active] => 1
        )
)

我可以使用以下代码来实现这一目标,但对我来说有点不客气:

# Set up the breadcrumbs:
if( !is_null($category->category) )
{
    $tpl['breadcrumbs'][2] = $tpl['breadcrumbs'][1];
    $tpl['breadcrumbs'][1] = [ 'title' => $category->category->name, 'text' => $category->category->name, 'url' => SITE_DOMAIN.ADMIN_PATH.'/items/' ];
}

是否可以在不编写自定义函数或不使用上述技巧的情况下,将数组项插入指定索引处的多维数组?

1 个答案:

答案 0 :(得分:2)

由于您要插入的项目是一个数组,并且array_splice接受一个项目数组,因此请将您的数组放入一个数组中。

此外,由于您想在最后一个元素之前插入内容,因此可以使用负数作为偏移量以从末尾开始倒数。 (效果与您获得的数据相同,但是对于不同大小的数组很重要。)

array_splice(
    $tpl['breadcrumbs'],
    -1,
    0,
    [[ 'title' => $category->category->name, 'text' => $category->category->name, 'url' => SITE_DOMAIN.ADMIN_PATH.'/items/' ]]
);