douzhang3822 2014-05-21 07:41
浏览 58

替换关联数组中的值?

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 (e.g. 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?

  • 写回答

3条回答 默认 最新

  • douqian2524 2014-05-21 07:47
    关注

    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.

    评论

报告相同问题?

悬赏问题

  • ¥15 HLs设计手写数字识别程序编译通不过
  • ¥15 Stata外部命令安装问题求帮助!
  • ¥15 从键盘随机输入A-H中的一串字符串,用七段数码管方法进行绘制。提交代码及运行截图。
  • ¥15 TYPCE母转母,插入认方向
  • ¥15 如何用python向钉钉机器人发送可以放大的图片?
  • ¥15 matlab(相关搜索:紧聚焦)
  • ¥15 基于51单片机的厨房煤气泄露检测报警系统设计
  • ¥15 Arduino无法同时连接多个hx711模块,如何解决?
  • ¥50 需求一个up主付费课程
  • ¥20 模型在y分布之外的数据上预测能力不好如何解决