duanfu1942 2018-05-31 15:12 采纳率: 100%
浏览 11
已采纳

从DB访问数据

I'm getting data from database and putting it in a variable $data. If I'll print_r($data), I'll get something like that:

Array
(
    [0] => stdClass Object
        (
            [id] => 1
            [name] => Bob
        )
    [1] => stdClass Object
        (
            [id] => 2
            [name] => Mike
        )
)

It has more [key] => value in each of them, and obviously it doesn't end on [1].

I'm using foreach() like that:

foreach ($data as $item) {
   foreach ($item as $key => $value) {
       //code
   }
}

I have two question regards all the above:

1) Is there less complex technique to get the $key and $value?

2) If, for example, I want to output only the [name], how would I access it? The $key[placeholder] while placeholder is a number is outputting the letter number value of the $key.

  • 写回答

1条回答 默认 最新

  • dongpo7467 2018-05-31 15:19
    关注

    You have an array with object, so if you want only the name:

    $name_list = array();
    
    foreach ($data as $obj) {
        $name_list[] = $obj->name;
    }
    

    This way you will have an array with only the name of each object.

    So to summarize :

    You loop through an array of obj, so to access the properties of each object just do :

    $obj->/* the properties */;
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度