Split Array into Smaller Arrays Based on Value of

2020-03-05 20:36发布

问题:

I have mysql search results from a keyword search being performed on my site. They're sorted by membership rank (0-3). However, I need to display the ranks differently than each other - like rank 3 gets more prominent formatting than the others.

I was thinking of splitting the rows up into individual arrays. So like array0 would contain all the rows that had the rank of 0, etc. Then loop through these arrays to display the results. I just have NO idea how to do this -- split the array up into smaller arrays.

(For reference, I found this question: splitting a large array into smaller arrays based on the key names but I wasn't really sure if that's what I needed... maybe some clarification on that q would help here?)

For example here is my array:

Array ( 
     [rank]         => 3 
     [organization] => Test Company 
     [imagecompany] => 1636.gif 
     [website]      => http://www.google.com 
     [phone]        => 344-433-3424 
     [fax]          => 
     [address_on_web] => physical   
     [address] => 2342 Test Ave 
     [city] => York 
     [stateprov] => WA 
     [postalcode] => 00000 
     [address_mailing] => 2342 Test Ave 
     [city_mailing] => Seattle 
     [state_mailing] => WA 
     [zip_mailing] => 00000 
     [description] => 'Test test Test test Test test Test test Test 

test Test test Test test Test test Test test Test test Test test Test test Test test 

Test test Test test'
     [customerid] => 1636 ) 

回答1:

You can use the rank as a key to create an multidimensional array like this:

$aRanks = array();
foreach($aArray as $aEntry) {
    $aRanks[$aEntry['rank']][] = $aEntry;
}
echo '<pre>';
print_r($aRanks);


回答2:

I have mysql search results from a keyword search

Then sort it using the database/SQL - not PHP. It's faster and uses less code.



回答3:

$query = mysql_query(); // your query here 
$result = mysql_fetch_array($query);
foreach($result as $row){
  switch($row['rank']){
    case 3: 
    // statement to apply formatting, add to each case
    // example:
    echo "<span style="color:red;">;
    break;
    case 2: break;
    case 1: break;
  }
}

Then output each row, echo closing </span> (or div or whatever) where you want the formatting to end



标签: php mysql arrays