字符串爆炸然后对由索引键定义的多个单个数组进行排序

字符串爆炸然后对由索引键定义的多个单个数组进行排序

问题描述:

使用php 5.3,我想对数组进行降序排序。 我有一个字符串后以下多单阵列爆炸:字符串爆炸然后对由索引键定义的多个单个数组进行排序

Array 
(
[0] => A 
[1] => 115 
[2] => 20 
) 
Array 
(
[0] => A 
[1] => 140 
[2] => 50 
) 
Array 
(
[0] => A 
[1] => 120 
[2] => 40 
) 

我要找的输出将排序key[1]升序所以它看起来是这样的:

Array 
(
[0] => A 
[1] => 115 
[2] => 20 
) 
Array 
(
[0] => A 
[1] => 120 
[2] => 40 
) 
Array 
(
[0] => A 
[1] => 140 
[2] => 50 
) 

的代码我目前为止是:

$data = string_content_to_explode 

foreach($data as $line) { 

    if(substr($line,0,1)=="A") { 

    $parts = explode(chr(9), $line); 

// sort awards DESC 
array_multisort($parts[1]); 
} 

echo "<pre>"; print_r($parts); echo "</pre>"; 

不幸的是,这并没有任何效果。 我找不到可以用这种方法对多个单个数组进行排序的foreach函数或示例。如果有人能指出我会朝着正确的方向发展,那将会很棒。

usort
+0

你看到这个http://php.net/manual/en/function.array-multisort.php了吗? –

+0

[按值排序多维数组]的可能重复(https://stackoverflow.com/questions/2699086/sort-multi-dimensional-array-by-value) – mickmackusa

排序它:

usort($string_content_to_explode,function($a,$b){ 
    if ($a[1] == $b[1]) 
     return 0; 
    return ($a[1] < $b[1])? -1: 1; 
}); 


var_dump($string_content_to_explode); 
+0

评论downoter)。是的,这是错误的。我检查/更新。附:周末愉快!)) – voodoo417

usort()是不必要的。 sort()将完美执行此任务,因为您可以在第一列然后第二列进行排序而不会出现任何打嗝。

代码:(Demo

$data=array('A'.chr(9).'115'.chr(9).'20','B'.chr(9).'DO NOT'.chr(9).'INCLUDE','A'.chr(9).'140'.chr(9).'50','A'.chr(9).'120'.chr(9).'40'); 

foreach($data as $line){ 
    if(strpos($line,'A')!==false){ // don't use substr($line,0,1)=="A", strpos is faster/better 
     $parts[]=explode(chr(9),$line); // create multi-dimensional array, instead of overwriting 1-dim array 
    } 
} 
sort($parts); // because first column is always "A", and you are sorting on the next column 
var_export($parts); // print to screen 

输出:

array (
    0 => 
    array (
    0 => 'A', 
    1 => '115', 
    2 => '20', 
), 
    1 => 
    array (
    0 => 'A', 
    1 => '120', 
    2 => '40', 
), 
    2 => 
    array (
    0 => 'A', 
    1 => '140', 
    2 => '50', 
), 
) 

P.S. OP最初要求DESC命令,但意味着ASC命令按预期结果进行判断。