简体   繁体   中英

How to make an object associative array in php

I am trying to select information from a db and store the information in an associative array. I have it working so far as to select the information and make an object which is stored in the array however I can't get the association to work. I want each book to be associated with the title.

When I try to push the association onto the array it is creating an array within an array.

public function getBookList()
    {
        $conn = mysqli_connect('localhost', 'root', '') or die ('No connection');
        mysqli_select_db($conn, 'books' ) or die (' database will not open');
        $query = "select title, author, description from book";  
        $result = mysqli_query($conn, $query) or die("Invalid query"); // runs query using
        // open connection

        $count = 0;
        $booksArray= array();
        while($row = mysqli_fetch_row($result))//  while there are rows available
        {

            $booksArray[$count] = new Book($row[0],$row[1],$row[2]);
            $count++;

            array_push($booksArray, array($row[0] => $tempBook));           

        }

        return($booksArray);
        mysqli_close($conn);
    }

Assign directly by the key into the array:

$booksArray[$count] = $tempBook = new Book($row[0],$row[1],$row[2]);
$booksArray[$row[0]] = $tempBook;           

Try this way

$booksArray[$row[0]] = $tempBook;

Also, I can't see where do you assign value to $tempBook , I guess new Book($row[0],$row[1],$row[2]) should be the value. So, inside while loop try:

$tempBook = new Book($row[0],$row[1],$row[2]);
$booksArray[$row[0]] = $tempBook;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM