dongwu3747 2014-07-16 14:03
浏览 31
已采纳

偏移打印关联对象数组中的数组键

I have a query that returns data from a database and stores the data in an array called $array.

Using a print_r($array) I receive data like:

Array
(
    [0] => stdClass Object
        (
            [Item1] => 1
            [Item2] => 1
            [Item3] => 1
            [Item4] => 'Az'
            [Item5] => 222
            [Item6] => 223
            [Item7] => 21
            [Item8] => 22
        )
) 

I've found I can return the keys Item1 to Item8 using:

foreach ($array[0] as $key => $a){
  echo '<pre>', $key, '</pre>';
}

However I'd only like to return from Item4 to the end of the array. (remove the first 3 items)

Note that query sometimes returns multiple rows i.e. $array[0], $array[1] but $array[0] will always exist if there's a result. I only need to get the keys from the array once as I'd like to use them as column headings in the table they are displayed in.

I would prefer a foreach() situation as I would only like to output as many columns as are present.

I've tried looking at array_slice() but I couldn't seem to get it to work, my efforts are displayed below:

$sliced =  array_slice($prices[0], 3, $preserve_keys = true);
foreach ($sliced as $key => $value){
  echo '<pre>'.$key.'</pre>';
}
  • 写回答

3条回答 默认 最新

  • dsw7547 2014-07-16 14:18
    关注

    The solution to Your problem lays deeper than You are trying to solve it.

    If the DB query returns an array with indexes 1..10 but You only want to display the data from index 4..10 then what You really need is to change the DB query to return only these columns 4..10.

    So basically instead of executing this query:

    SELECT * FROM table1
    

    You need to execute query such this:

    SELECT col4, col5, col6, col7, col8, col9, col10
    FROM table1
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥60 求一个简单的网页(标签-安全|关键词-上传)
  • ¥35 lstm时间序列共享单车预测,loss值优化,参数优化算法
  • ¥15 基于卷积神经网络的声纹识别
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP