You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PHP多维数组添加class键值对,如何避免生成嵌套数组?

问题:为PHP数组添加指定键值对避免嵌套结构

原数组

Array (
    [link] => Array (
        [title] => FY 2020/21
        [url] => http://local.abc.com/app/uploads/2022/01/A.pdf
        [target] =>
    )

    [show_icon] => 
)

需求

检查show_icon是否有值,为link数组添加名为class的键值对,期望结果:

Array (
    [link] => Array (
        [title] => FY 2020/21
        [url] => http://local.abc.com/app/uploads/2022/01/A.pdf
        [target] =>
        [class] => 'A string of classes'
    )

    [show_icon] => 
)

尝试的代码及错误输出

尝试使用array_push实现,但得到了嵌套结构的错误输出:

$class = ['class' => 'btn-apply type2'];

if ($link['show_icon']) {
    $class = ['class' => 'btn-apply type2 show-icon'];
}

if (is_array($link['link'])) :
    array_push($link['link'], $class);
endif;

执行后输出:

Array (
    [link] => Array (
        [title] => FY 2020/21
        [url] => http://local.abc.com/app/uploads/2022/01/A.pdf
        [target] => 
        [0] => Array (
            [class] => btn-apply type2
        )
    )

    [show_icon] => 
)

解决方案

方法1:直接赋值(最简洁)

不需要把class包装成数组,直接给link数组的class键赋值即可:

$class = 'btn-apply type2';
if ($link['show_icon']) {
    $class = 'btn-apply type2 show-icon';
}

if (is_array($link['link'])) {
    $link['link']['class'] = $class;
}

方法2:使用array_merge合并数组

如果需要合并多个键值对,可以用array_merge将原link数组和包含class的数组合并:

$classArr = ['class' => 'btn-apply type2'];
if ($link['show_icon']) {
    $classArr = ['class' => 'btn-apply type2 show-icon'];
}

if (is_array($link['link'])) {
    $link['link'] = array_merge($link['link'], $classArr);
}

错误原因说明

array_push的作用是将传入的参数作为新元素添加到数组末尾,你传入的$class是一个数组,所以它会被当成单个元素(索引为0)插入到link数组中,形成嵌套结构。而我们需要的是将class作为link数组的一个键直接添加,因此直接赋值或数组合并才是正确的方式。

内容的提问来源于stack exchange,提问作者Jason Is My Name

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.05 00:15:28