开发者

Sort multi-dimensional array built from CSV data using PHP

开发者 https://www.devze.com 2023-01-29 02:45 出处:网络
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

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 = ar开发者_JS百科ray_shift($rows);
foreach ($rows as $row) : list($ShowKey, $ShowFeedURL, $ShowLink, $ShowIcon, $ShowTitle, $ShowTag, $ShowCategory, $ShowEps, $ShowLastUpdate, $ShowNew) = $row;

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


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.


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/


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


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消