0

我需要搜索这个数组:

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

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

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

如果(例如)模型是“Civic”,则将该“汽车”放在位置 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

4

4 回答 4

1

你的意思是:


function sortByModel($a, $b) {
    if($a["model"] == "Civic") {
        return 0;
    }
    else {
        return 1;
    }       
}
usort($a, 'sortByModel');
echo "<pre>";
print_r($a);
于 2012-04-05T11:26:11.267 回答
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;
        }
    }
}
?>
于 2012-04-05T11:32:30.870 回答
0

或者也许这就是你想要的(至少输出是你想要的)

foreach($cars as $k => $v){
    if ($v['model'] == 'Civic'){
        unset($cars[$k]);
        array_unshift($cars, $v);
    }
}
于 2012-04-05T11:31:57.917 回答
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'));
于 2012-04-05T11:42:55.577 回答