【问题标题】:Appending a row title along with a value to an array within an array将行标题和值附加到数组中的数组
【发布时间】:2023-01-13 22:57:23
【问题描述】:

我有一系列链接:

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

    [show_icon] => 
)

我必须检查 [show_icon] 是否有值并向 [link] 附加一行,称为类。

我希望它看起来像这样:

    [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、array_merge、交换到 stdObject ...

这是我的代码:

$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] => 
)

如何在没有 [0] => Array ( 环绕 [class] 的情况下添加到数组?

【问题讨论】:

    标签: php arrays object


    【解决方案1】:

    您可以将类直接添加到 $link 数组,而不是使用 $class 创建一个新数组,然后将其推送到现有数组。例如,您可以使用以下代码:

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

    【讨论】:

      猜你喜欢
      • 2021-03-05
      • 1970-01-01
      • 1970-01-01
      • 2017-08-19
      • 1970-01-01
      • 2018-12-19
      • 2020-03-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多