Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
90 views
in Technique[技术] by (71.8m points)

php - 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;
question from:https://stackoverflow.com/questions/65902142/how-to-add-element-to-advanced-array-inside-foreach-loop

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...