PHP数组 - 显示未使用的变量

时间:2011-08-10 09:54:30

标签: php arrays

让我说我有

<?php 

$type[ford][focus] = 'some text';
$type[ford][fiesta] = 'some text';

$type[toyota][corola] = 'some text';
$type[toyota][avensis] = 'some text';

$type[bmw][x6] = 'some text';
$type[bmw][x5] = 'some text';

$type[audi][a6] = 'some text';
$type[audi][a8] = 'some text';



function show($car){

foreach ($car as $model)
{
echo $model;
}

}



echo 'Best cars';
show ( $type[bmw] );

echo 'Other cars';
show ( $type[ford] );


?>

我需要的是在最后一个功能中显示未使用的其余车辆(奥迪和丰田)。所以show($ type [ford])应该显示福特,奥迪和丰田汽车。

提前谢谢。

3 个答案:

答案 0 :(得分:1)

我正在制作原始变量的副本,但是如果在此之后不再使用它,你也可以修改原始变量。

$cars = $type;

echo 'Best cars';
show ( $type[ 'bmw' ] );
unset( $cars[ 'bmw' ] );

echo 'Other cars';
foreach( $cars as $car ) {
    show( $car );
}

答案 1 :(得分:0)

我无法看到数组中的项是如何“使用”的,因为函数不在代码中,但我建议在函数中使用unset(),然后数组中剩下的所有项都是没用了。

答案 2 :(得分:0)

还使用unset(),但重写show()来完成工作:

function show($car){
  foreach ($car as $model)
  {
    if(is_array($model)) {
      show($model);
    } else {
      echo $model;
    }
  }
}

$cars = $type;

echo 'Best cars';
show ( $type[ 'bmw' ] );
unset( $cars[ 'bmw' ] );

echo 'Other cars';
show($cars);

这样,您可以更改$ cars以获得更多级别(例如,模型的年份),您不必更改代码。

相关问题