Home > Software engineering >  Appending a row title along with a value to an array within an array
Appending a row title along with a value to an array within an array

Time:01-17

I have an array of links:

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

    [show_icon] => 
)

I must check if [show_icon] has a value and append an additional row to [link], called class.

I wish for it to appear like so:

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

I have tried running loads of different methods to append, such as array_push, array_merge, swap to a stdObject...

This is my code:

$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;

With the output being:

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

How do I add to the array without [0] => Array ( wrapping around the [class]?

CodePudding user response:

You can add the class directly to the $link array instead of creating a new array with $class and then pushing it onto the existing array. For example, you can use the following code:

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