问题
I have
$finalprint[$counting] = $ppn.' '.$ppn2;
By using loop i have saved some data into the array. Now have also done the sorting.
arsort($finalprint); // i think this would arrange the data into descending order by $counting
Now I have data's like
$finalprint[426] = "XYZ"
$finalprint[124] = "ABC"
$finalprint[333] = "MNO"
How i can print the values of this array, like XYZ MNO ABC
?
回答1:
if you want to sort according to values in desc order
$finalprint[] = "XYZ";
$finalprint[] = "ABC";
$finalprint[] = "MNO";
rsort($finalprint);
foreach ($finalprint as $val) {
echo $val." " ;
}
o/p XYZ MNO ABC
if you want to sort according to keys in desc order
krsort($finalprint);
foreach ($finalprint as $val) {
echo $val." " ;
}
o/p MNO ABC XYZ
回答2:
join(' ', array_values($finalprint));
回答3:
if you want to print the contents in your requested order, try ordering the array values. array_reverse
helps:
$finalprint = array();
$finalprint[426] = "XYZ";
$finalprint[124] = "ABC";
$finalprint[333] = "MNO";
//sort by key ascending
asort($finalprint);
//getting the keys and reversinf them
$keys = array_reverse(array_keys($finalprint));
//iterating over the keys
foreach ($keys as $key) {
echo $key.'=>'.$finalprint[$key].PHP_EOL;
}
回答4:
Use arsort to sort the values in reverse order or krsort to sort the keys in reverse order. (It is not clear from your example which one you want)
arsort($finalprint);
echo implode(' ', $finalprint);
Documentation : implode
回答5:
krsort( $finalprint );
echo join( " ", $finalprint );
But are you saying the array is sorted into XYZ
, ABC
, MNO
order, or XYZ
, MNO
, ABC
order?
来源:https://stackoverflow.com/questions/11950704/print-array-values