2012-04-05 53 views
0

開始我需要搜索這個數組:PHP搜索多維數組的值,然後將這個元素在陣列

cars - 
     [0] -make : Ford 
      -model: Escort 
      -year: 1991 

     [1] -make: Honda 
      -model: Civic 
      -year: 1996 

     [2] -make: Vauxhall 
      -model: Astra 
      -year: 1972 

如果(例如)的模式是「公民」,地方「車」在位置0

所以端陣列將是這樣的:

cars - 
     [0] -make: Honda 
      -model: Civic 
      -year: 1996 

     [1] -make : Ford 
      -model: Escort 
      -year: 1991   

     [2] -make: Vauxhall 
      -model: Astra 
      -year: 1972 

我已經嘗試了一些usort變化:

function typeSort($a, $b) 
    { 
     if ($a['model'] == 'Civic') 
     { 
      return 0; 
     } 
     return ($a['model'] < $b['model']) ? -1 : 1; 
    } 

但這只是返回1

回答

1

你的意思是:


function sortByModel($a, $b) { 
    if($a["model"] == "Civic") { 
     return 0; 
    } 
    else { 
     return 1; 
    }  
} 
usort($a, 'sortByModel'); 
echo "<pre>"; 
print_r($a); 
0

或者也許這是你想要的(輸出是期望至少)

foreach($cars as $k => $v){ 
    if ($v['model'] == 'Civic'){ 
     unset($cars[$k]); 
     array_unshift($cars, $v); 
    } 
} 
0
<?php 
$cars = array(
    0=>array(
     'make' => 'Ford' 
     ,'model' => 'Escort' 
     ,'year' => 1991 
    ) 
    ,1=>array(
     'make' => 'Honda' 
     ,'model' => 'Civic' 
     ,'year' => 1996 
    ) 
    ,2=>array(
     'make' => 'Vauxhall' 
     ,'model' => 'Astra' 
     ,'year' => 1972 
    ) 
); 

var_dump("BEFORE",$cars); 
var_dump("AFTER",array_typesort($cars)); 

function array_typesort($arr, $model='Civic') { 
    foreach ($arr as $k => $v) { 
     if ($arr[$k]['model'] == $model) { 
      $out = array_splice($arr, $k, 1); 
      array_unshift($arr, $out[0]); 
      return $arr; 
     } 
    } 
} 
?> 
0

您可以試試這個:

function typesort($arr, $val) 
{ 

foreach($arr as $key=>$value) 
{ 
    if(in_array($val,$value)) 
    { 
     $tempArr = $value; 
     unset($arr[$key]); 
     break; 
    } 
} 
array_unshift($arr,$tempArr); 
return $arr; 
} 

print_r(typesort($data,'bbb'));