douju1852 2013-02-19 09:14
浏览 34
已采纳

使用php数组中的第n项

I have created an array, as follows:

$results = array();
do {
  $results[] = $row_products;
} while ($row_products = mysql_fetch_assoc($products));

print_r($results);

This prints out the array like this:

Array ( 
[0] => Array ( 
       [productName] => product1 
       ) 
[1] => Array ( 
       [productName] => product2 
       ) 
[2] => Array ( 
       [productName] => product3 
     )

I want to now use say the second item in the array in another mysql query.

But I cannot define it. I have tried

$results[1];

but this does not work. So in effect, if I echo the second item, it would print 'product2'.

  • 写回答

2条回答 默认 最新

  • dongza1708 2013-02-19 09:16
    关注

    You should learn the basics about arrays here: http://www.php.net/manual/en/language.types.array.php

    You are using a nested array, so you have the access it like this:

    echo $results[1]['productName'];
    

    Another solution would be to use $results[] = $row_products['productName']; and then just echo $results[1].

    In addition, you should use a while loop instead of a do/while loop because $row_products does not seem to be defined for the first iteration.

    while ($row_products = mysql_fetch_assoc($products)) {
      $results[] = $row_products;
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?