dtng25909 2017-11-05 04:00
浏览 103
已采纳

PHP数组乱序

I am pulling information from a database- from two different tables. The origins of the data is a single archival document- so each row from the two tables has a unique value- line number.

So the code is as follows

//get data about the report as a whole.
$sql = "SELECT * FROM reports_list WHERE report_key ='" . $report_key . "'";
$report_data = $wpdb->get_results ($sql);

//Time to start building the file to go out.

$total_report = array();
foreach($reports_in_db as $key)
{
    $total_report [$key->line_number] = $key;                       
}
// get subtitles/abstract
$sql = "SELECT line_number, field_text FROM subtitle_abstract_summary WHERE report_key = '" . $report_key . "'";            
$abs_sums = $wpdb->get_results ($sql);
//now for a series of conditional things
if (empty($abs_sums))
{
    //echo "subtitles/abstracts"
}
else
{
    foreach ($abs_sums as $key)
    {
        $total_report [$key->line_number] = $key;
    }
}

So what I expected to happen, is to create an array where the main data rows have the subtitles rows interspersed. What actually happens is that $total_report has all the main data rows, followed by all the subtitles rows. When I print_r the array, they're not in the order I expect.

for example, if the data rows are row 1-200, and the subtitle rows are 121, 161, and 181, this code produces an array that has elements 1-120, 122-160, 162-180, then 121,161 and 181 in that order.

Currently, the elements are WPDB objects. If possible, I'd like to be able to just get them in the right order. If there's also a simple way to just sort by the element number, that's okay too.

I've tried doing sort() on $total_report- but that sorted by the alphabetical value of the first field of the object..

I'm honestly just puzzled why the array doesn't have the elements in the order I thought they'd be in.

Thanks

  • 写回答

1条回答 默认 最新

  • duanfei1930 2017-11-05 04:16
    关注

    Use ksort() to sort array by keys. And SORT_NUMERIC flag so it would sort it as numbers:

    <?php
       ...
       ksort($total_report,SORT_NUMERIC);
       ...
    ?>
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 oracle集群安装出bug
  • ¥15 关于#python#的问题:自动化测试
  • ¥20 问题请教!vue项目关于Nginx配置nonce安全策略的问题
  • ¥15 教务系统账号被盗号如何追溯设备
  • ¥20 delta降尺度方法,未来数据怎么降尺度
  • ¥15 c# 使用NPOI快速将datatable数据导入excel中指定sheet,要求快速高效
  • ¥15 再不同版本的系统上,TCP传输速度不一致
  • ¥15 高德地图2.0 版本点聚合中Marker的位置无法实时更新,如何解决呢?
  • ¥15 DIFY API Endpoint 问题。
  • ¥20 sub地址DHCP问题