Sort multi-dimensional array built from CSV data using PHP

隐身守侯 提交于 2019-12-31 06:10:54

问题


Trying to sort an array in PHP that is being populated from a CSV. I would also, ideally, LOVE to be able to control the sort by clicking on tabs in the table here .. Right now, though, my first task at hand is just sorting the damn thing.. been working on this for over 3 days now.. any help is GREATLY appreciated!! Cheers!

PHP

<?php 

$fp = fopen("https://spreadsheets.google.com/pub?key=0AjZgwY03sLMGdHVoWjhucGowWWJBb2g2NnQzVG9HZFE&hl=en&single=true&gid=0&output=csv","r"); 
$rows = array(); 
while (($row = fgetcsv($fp)) !== FALSE) { 
    $rows[] = $row; 
}
fclose($fp); 

$headers = array_shift($rows);
foreach ($rows as $row) : list($ShowKey, $ShowFeedURL, $ShowLink, $ShowIcon, $ShowTitle, $ShowTag, $ShowCategory, $ShowEps, $ShowLastUpdate, $ShowNew) = $row;

$oddpost = ( empty( $oddpost ) ) ? '_odd' : ''; ?>

回答1:


Instead of sorting the table in PHP, you may consider doing it client-side in Javascript. For instance have a look at this jQuery plugin: http://tablesorter.com/




回答2:


I recently did this. I had a multi-dimensional array of records from a database, and I needed to sort them based off of one specific column in the array. Here's what I did:

foreach($TimeRecords as $key => $value)
{
   $Rates[$key] = $value['rate'];
}
array_multisort($Rates, SORT_ASC, $TimeRecords);

I build an array of only the column I need, then I use the array_multisort() function to sort the array based off of that column.

You can write functions that will do this in PHP and then just call them with javascript ajax calls and reload that part of the page when it's done sorting.




回答3:


You may find usort() function helpful. It accepts callback argument, which may be used for sorting by specific field.




回答4:


I had a similar issue to this today. Basically what I ended up doing is creating a temporary table which I loaded in the rows from the csv file that I needed. From there, I used php to sort and organize the data and update or add to the table I needed to alter.

Example, I made a table called 'temp' and loaded in all the rows of the category I needed. Then, once this was in the table, I made a php script which sorted the information by number of total sales in descending order. From there, I did a query to update my main table and used a limit to control this (only the top 200 items by number of sales).

It was very easy to do and hopefully it will help you or someone else.

Keep in mind. If you're going to do this more than once, you will need to truncate the temporary table to remove the old rows first.



来源:https://stackoverflow.com/questions/4380317/sort-multi-dimensional-array-built-from-csv-data-using-php

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!