dongyan2445 2018-10-30 10:18
浏览 62
已采纳

获取php对象的最后500个值?

I know the PHP end() function exists, but i don't just want the last value of the object, i want the last 500 values.

I have an object with possibly thousands of data and i want to show a graph on my frontend with this data. But only the last 500 values as more than that could slow down the response time too much.

I was thinking of maybe reversing the values of the data object, take the first 500 values and then reverse it back again. This just sounds like too much wasted processing.

I've also tried to first convert the object to an array and then using the array_slice($array, -500); and the converting it back to a PHP object and use it in a foreach. When i do this, i get the error:

Invalid argument supplied for foreach()

This is the code:

$dataArray = array_slice((array) $data, -5);
$data = json_encode($dataArray);

Do you have any ideas what i'm doing wrong here or how to do this smarter?

  • 写回答

2条回答 默认 最新

  • douxing5199 2018-10-30 10:24
    关注

    if your $data object is a collection of items, you can use the following:

    $data->reverse()->take(500)->get();
    

    or transform your array into a collection

    collect($data)->reverse()->take(500)->get();
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 adb push异常 adb: error: 1409-byte write failed: Invalid argument
  • ¥15 android报错 brut.common.BrutException: could not exec (exit code = 1)
  • ¥15 nginx反向代理获取ip,java获取真实ip
  • ¥15 eda:门禁系统设计
  • ¥50 如何使用js去调用vscode-js-debugger的方法去调试网页
  • ¥15 376.1电表主站通信协议下发指令全被否认问题
  • ¥15 物体双站RCS和其组成阵列后的双站RCS关系验证
  • ¥15 复杂网络,变滞后传递熵,FDA
  • ¥20 csv格式数据集预处理及模型选择
  • ¥15 部分网页页面无法显示!