简体   繁体   中英

Replacing a value in an associative array?

I have this:

foreach ($books as $book)
{
    $catname = get_category_name($book['category']);
    $book['category'] = $catname;
}
print_r($books);

Right now, $book['category'] represents an integer value, which references the ID of a row in a category table of the database (eg ID 1 = Fiction). As you can guess, get_category_name($id) takes an ID and finds the correct row, and returns the name of the category. The function works correctly, and if i print_r($catname) in the foreach it prints the names of the categories, like it should.

I have an associative array called $books that gets filled from every row in the book table in the database. What I want to do, is take the category integer value of each book element and use get_category_name($id) to replace that integer value with the actual category name.

The problem I am having is that I cannot replace the integer value that already exists at $book['category'] with the actual category name which resides in $catname . When I use print_r($books) to see if the changes were made in the foreach , they confirm the changes do not get made.

How can I fix this?

I think you want something like this?

foreach ($books as &$book)
{
    $catname = get_category_name($book['category']);
    $book['category'] = $catname;
}
print_r($books);

Notice the &$book.

You either use foreach($books as &$book) and edit $book . This way you have a reference to the real book element inside the array in stead of a copy of it. Beware that if you want to do this multiple times on the same array, you will need to reset the array each time after use. See: http://nl1.php.net/reset

Or you use foreach($books as $key=>$value) and edit $books[$key] . This way you get copies of the books and their keys. But you then use the key on the original array.

THe problem is that in fact you do not change $books but $book , that is why you cant see changes in $books . Possible solution:

foreach ($books as $booksId => $book) //$booksId will contain current index in $books
{
    $catname = get_category_name($book['category']);
// now you can change correct index in $books:
    $books[$booksId]['category'] = $catname;
}

Edit: @Cardinal solution with refference is also correct.

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