简体   繁体   English

基于Key的值将阵列拆分成更小的阵列?

[英]Split Array into Smaller Arrays Based on Value of Key?

I have mysql search results from a keyword search being performed on my site. 我在我的网站上执行关键字搜索的mysql搜索结果。 They're sorted by membership rank (0-3). 他们按会员等级排序(0-3)。 However, I need to display the ranks differently than each other - like rank 3 gets more prominent formatting than the others. 但是,我需要以不同的方式显示排名 - 比如排名3比其他排名更加突出。

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. 因此,array0将包含排名为0的所有行等。然后循环遍历这些数组以显示结果。 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?) (作为参考,我发现了这个问题: 根据键名称将一个大数组拆分成较小的数组,但我不确定这是否是我需要的......也许对q的一些澄清会对这有帮助吗?)

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 ) 

You can use the rank as a key to create an multidimensional array like this: 您可以使用rank作为键来创建一个多维数组,如下所示:

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

I have mysql search results from a keyword search 我有关键字搜索的mysql搜索结果

Then sort it using the database/SQL - not PHP. 然后使用数据库/ SQL对其进行排序 - 而不是PHP。 It's faster and uses less code. 它更快,使用更少的代码。

$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 然后输出您想要格式化结束的每一行,echo closing </span> (或div或其他)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM