|
 |
beginning_php thread: Sorting Arrays
Message #1 by celeborn@f... on Mon, 3 Feb 2003 06:21:37
|
|
Hello everyone,
I am having a problem with an array I am working with. It has the form
$Data[$counter][$datatype] = $value
What I need to do is be able to sort based on $value of a certain
$datatype value.
For example if I did:
$Data[1][car] = "civic";
$Data[1][truck] = "ram";
$Data[2][car] = "accord";
And I want to sort the value of cars, how do u do this? I have found how
to do it with a simpler array but nothing on how to do it under these
circumstances. Any help that can be provided on this would be most helpful.
Sincerely
Mychael
Message #2 by "Gellings, C.O." <gellingsco@p...> on Mon, 03 Feb 2003 09:01:31 +0100
|
|
As far as I can see it is not possible because of your prefix to cars [1] / [2]
You can swith your array build-up $Data[car][1], $Data[car][2],
$Data[truck][1] etc then you have the numbers you can run through with for
/ foreach / or while(list(...
Or you can store your data in a simple array $Data and use car1 car2 etc as
key (same for truck) and than you can use asort() or arsort()
if you want to get al the cars you run through the query like
while (list ($key, $val) = each ($Data)) {
echo "$key = $val\n";
}
m.t.h.
Carl
Message #3 by "Nikolai Devereaux" <yomama@u...> on Mon, 3 Feb 2003 11:20:09 -0800
|
|
> I am having a problem with an array I am working with. It has the form
>
> $Data[$counter][$datatype] = $value
>
> What I need to do is be able to sort based on $value of a certain
> $datatype value.
>
> For example if I did:
> $Data[1][car] = "civic";
> $Data[1][truck] = "ram";
> $Data[2][car] = "accord";
>
> And I want to sort the value of cars, how do u do this? I have found how
> to do it with a simpler array but nothing on how to do it under these
> circumstances. Any help that can be provided on this would be most helpful.
The cleanest way to do this is to probably separate each grouping (cars and
trucks) and sort those.
I don't see any benefit to merging the two groups together, though.
$cars = array();
$trucks = array();
foreach($Data as $vehicle_array)
{
foreach($vehicle_array as $type => $model)
{
if($type == "car")
{
$cars[] = $model;
}
else
{
$trucks[] = $model;
}
}
}
sort($cars);
sort($trucks);
reset($cars);
reset($trucks);
Take care,
Nik
|
 |