PHP arrays - display unused vars
Lets say I have
<?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 ( $ty开发者_如何学运维pe[bmw] );
echo 'Other cars';
show ( $type[ford] );
?>
What I need is that the rest of cars that are not used (audi and toyota) to be displayed in the last function. So show ( $type[ford] ) should display ford, audi and toyota cars.
Thank you in advance.
I'm making a copy of the original variable here, but you can modify the original too if it's not used anymore after this.
$cars = $type;
echo 'Best cars';
show ( $type[ 'bmw' ] );
unset( $cars[ 'bmw' ] );
echo 'Other cars';
foreach( $cars as $car ) {
show( $car );
}
I can't see how the items in the array are 'used' as the function isn't in the code but I would recommend using unset()
in the function then all that's left in the array is items that are unused.
Also using unset(), but rewriting show() to do the work:
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);
This way, you could change $cars to have more levels (for example, the year of the model) and you wouldn't have to change the code.
精彩评论