Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/arrays/13.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
PHP数组-显示未使用的变量_Php_Arrays - Fatal编程技术网

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

PHP数组-显示未使用的变量,php,arrays,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 tex

假设我有

<?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])应该展示福特、奥迪和丰田汽车


提前谢谢。

我在这里复制原始变量,但如果此后不再使用,您也可以修改原始变量

$cars = $type;

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

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

我看不出数组中的项是如何被“使用”的,因为函数不在代码中,但我建议在函数中使用
unset()
,那么数组中剩下的就是未使用的项。

也使用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更改为具有更多级别(例如,型号的年份),而不必更改代码。

如果数组键是字符串,请引用它们
$type[ford]
是错误的,如果您激活了错误报告,就会看到这一点。那必须是
$type['ford']
@LoWE:你懂递归吗?如果是这样的话,那么这就是你所需要的。如果没有,试着读一篇像这样的文章。@André:我一定完全误解了这个问题,但我不知道递归与此有什么关系。我的建议是在show()中重用foreach,使其成为递归函数。@André:我想看一个例子。我不太清楚你的意思。有趣!不确定我是否会在这里使用它,但我可以在其他情况下看到它的用途。