Skip to content
Advertisement

How to add element to advanced array inside foreach loop

I am trying to add my data to my array inside my foreach loop.

I have almost done it successfully, except the array is too in-depth.

It’s showing array->array->{WHAT I WANT} When I need array->{WHAT I WANT}

Example, I’m needing it to be like:

Array
(
[home] => Array
    (
        [0] => DashboardMain@index
        [1] => GET
    )

[home/] => Array
    (
        [0] => DashboardMain@index
        [1] => GET
    )
)

When at the moment, it’s showing:

Array
(
[0] => Array
    (
        [services/content-writing] => Array
            (
                [0] => DashboardServices@contentwriting
                [1] => GET
            )

    )

[1] => Array
    (
        [services/pbn-links] => Array
            (
                [0] => DashboardServices@pbnlinks
                [1] => GET
            )

    )
)

The code I’m currently using inside my foreach loop is:

$realArray = array();

// Services exist
if($services)
{
    // Sort them into our array
    foreach ($services as $service) {

        $servicePageName = $service->page_name;
        $serviceName = str_replace(' ', '', strtolower($service->name));

        $realArrayNew = array(
            "services/$servicePageName" => ["DashboardServices@$serviceName", 'GET']
        );

        array_push($realArray, $realArrayNew);

        //'home' => ['DashboardMain@index', 'GET'],

    }
}

return $realArray;

Advertisement

Answer

This portion of the code inserts a new subarray to your main array:

$realArrayNew = array(
    "services/$servicePageName" => ["DashboardServices@$serviceName", 'GET']
);

array_push($realArray, $realArrayNew);

Replace it all with:

$realArray["services/$servicePageName"] = ["DashboardServices@$serviceName", 'GET'];

That way your top level will have service names as keys.

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement