'Fill an array with multiple arrays with an foreach loop in php

I have a problem which I cant figure out. I have an array $navItems. In there I have multiple arrays with the items.

print_r($navItems)

$navItems = array(
    array(
        "url" => 'index.php',
        "title" => 'Home',
        "id" => 1
    ),
    array(
        "url" => "pages/projects.php",
        "title" => "Projects",
        "id" => 2
    ),
    array(
        "url" => "pages/about.php",
        "title" => "About",
        "id" => 3
    ),
    array(
        "url" => "pages/contact.php",
        "title" => "Contact",
        "id" => 4
    ),
    array(
        "url" => "pages/login.php",
        "title" => "Login",
        "id" => 5
    ),
);
// Database conectie en query
$dbh = getDbConnection();
$sql = "SELECT * FROM pages";
$pages = $dbh->query($sql);


// Navitems 
$navItems = array();

foreach($pages as $singe_page){
    $page_title = $singe_page['title'];
    $page_url =$singe_page['url'];
    $page_id = $singe_page['id'];
    
    $pagina = array(
        'title' => $page_title,
        'url' => $page_url,
        'id' => $page_id
    );

    array_push($navItems, $pagina);
}
//This is the code on my array.php page. And it loads that in on the head.php

But now I want to add all the page arrays with an foreach loop. Because I have the pages saved in my database. And now I'm trying to pull the pages out my database and put them in the array.

But I just don't know anymore...

I just want for every record in my database it to throw that in an array and that array in the $navItems array.

Nevermind. When I was typing this I changed a little bit of code. And now it works. I added the array_push($navItems, $pagina) in the foreach loop. And it works.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source