Tracking Forums, Newsgroups, Maling Lists
Home Scripts Tutorials Tracker Forums
 
  HOME    TRACKER    PHP




How Do I Sort My Two Dimensional Array?


How do I sort my two dimensional array? I want to sort "numb" numerically, then "part" alphabetically. Code:




View Complete Forum Thread with Replies

See Related Forum Messages: Follow the Links Below to View Complete Thread
How Can I Sort A Multi-dimensional Array?
How can I sort a multi-dimensional array?

For instance:
a[Name], a[adress], a[number of messages].

How to sort on the item of number of messages?

Sort 2 Dimensional Array Alphabetically By Second Field In Each Row
Is there an easy way to sort a 2 dimensional array alphabetically by
the second field in each row?

Also, when I use sort() on a two dimensional array, it seems to work a
lot like array_reverse().

How To Sort 2 Dimensional Array By Primary And Secondary Column?
I think I figured out how to use array_multisort to sort by a primary
index. But how can i make it sort by a secondary index?

Assigning A Multi-dimensional Array To & From A Session Variable Loses The Array
I have created a multidimensional array and then assigned that array to a session variable so that I can use it easily on another page.  However, when I go to the array later, there's never anything in it. Code:

Finding Elements Of An Array In Another Multi-dimensional Array
So I have 2 arrays:
one contains userids. It may look like:
user_id[0] =12,
user_id[1] =30,
user_id[2] =43

The other is a multi-dimensional array with fields like:
user_info [0] = Array
(
[user_id] =13
[user_flag] =1
[url] =http://www.example.com?index,0
)
user_info[1] =Array
{
Array
(
[user_id] =120
[user_flag] =1
[address] =1234 Main St, Anytown, USA
[url] =http://www.yahoo.com
)
user_info[2] =Array
{
Array
(
[user_id] =130
[user_flag] =1
[address] =134 Main St, Anytown, USA
[url] =http://www.google.com
)

Array Sorting Blues....2 Dimensional Array
I have a 2 dimensional array where one col contains a Unix style date and the other contains a filename. I read through a directory to get this info. I can load the array and print it out just fine, but I can't seem to sort it using any of the sort functions! I want to reverse sort them, since they are news stories that I want to display in the correct order by date. When I try to sort I get a "Warning: Cannot compare arrays or objects" message. I have the feeling it's something stupid on my part but can't find any good examples anywhere.

Anyone have an idea about this?

P.S. I know a database would solve this but sadly it's not an option for me right now...

Turn Array Into Multi-dimensional Array?
How can I take an existing array and turn it into a multi-dimensional array? I want to get a single row out of a MySQL table and have it in an array, but have along side the values the true field (column) length for each of the fields from the table. Here's my stab at it:

$userDetails = mysql_fetch_array($resultID);
$i = 0;
while ($i < mysql_num_fields($resultID))
{
    $userDetails[$i][2] = mysql_field_len($resultID, $i);
    $i++;
}

And I guess the follow up question (if this is indeed possible) is will this work with a multi-row return from the DB also?

Sorting Sql Results In An Array Using Things Outside The Array To Sort Them?
I'm using PHP to connect to a database full of place names, and their associated post codes, latitude and longitude on the earth. A user types his or her post code into a form, plus a distance (in miles), and the script looks for other area codes (first half of the post code) within that distance.

I can do that fine, but the results are ordered alphabetically by postcode, and I want to order it by the distance. Problem here, is that the distance isn't part of the array taken from the database, it takes the latitude and longitude of the area it's on in the while loop, and calculates the distance between the user's post code and that one, but it's not part of the array, so I can't sort the array using it.

How can I sort it? Can I add the calculated distances to the array, and sort it using sort()? If yes, how do I add them to the array?

Here's the page, just to explain better what the script does: http://navimaker.org/ed/owain/results.php?postcode=gl15&distance=34
Mess around with the postcode and distance vars.

I'd put the source on here too but I'm doing all this over SSH and can't copy & paste very easily .

"Array To String Conversion" Error When Constructing A Multi-dimensional Array
I'm a bit stumped as I am getting a "Notice: Array to String
Conversion" error when trying to do something that on the surface
should be a very simple task - create an array, and write a set of
values to them based on data submitted from POST Fields.

Code below:

$_SESSION["increment"] = array();
$x = 0 // Counter - This will be
incremented

$_SESSION["increment"][$x] = array("increment_bond" =>
$_POST["increment_bond"],
"increment_amount" = $_POST["increment_amount"],
"increment_comm_date1" = $_POST["increment_comm_date1"],
"increment_comm_date2" =$_POST["increment_comm_date2"],
"increment_comm_date3" = $_POST["increment_comm_date3"]);

It keeps throwing out that error, and does not write any of the POST
Values to the array (the POST values are definitely getting sent, so
that is not the problem).

If I dump out the value of $_SESSION["increment"], I get "1A" ?!?

I'm sure that there is a pretty simple mistake lurking somewhere - I
just can't seem to figure it out.

PHP 4 OO Issue - 3 Dimensional Array
Hello, I have this simple script that i have a 3 dimensional array. However I am kinda new to OO php, and it keep getting the same error? Any ideas?

class maps{

//Initalize the city array
var $City = array();
$City['city1']['Dundas']['Codes'] = "L9H, L85"; //ERROR LINE
$City['city1']['Dundas']['Amount'] = 13915;
$City['city2']['North Burlington']['Codes'] = "L7M, L7P";
$City['city2']['North Burlington']['Amount'] = 19668;
$City['city3']['South Oakville']['Codes'] = "L6K, L6L, L6M";
$City['city3']['South Oakville']['Amount'] = 26044;

function display_cities(){
echo "hi";
foreach($this->City as $kCity=>$vCity){
echo $kCity." = ".$vCity."<br>";
}
echo "bye";
}
}

Error is in this class file on the line noted.
Parse error: syntax error, unexpected T_VARIABLE, expecting T_FUNCTION

This is probably really simple, but i've been looking at it for a couple hours and cant figure it out.

Two Dimensional Array Problem
I want to put the contents of a csv file into a 2 dimensional array so that
I can access any element in a $table[x][y] manner and have come up with the
following code:

$complete = file("source.csv");
$row=0;
foreach ($complete as $value) {
$data = explode(",", $value);
$table[$row] = $data;
$row++;
}
echo "$table[6][4]";

However the echo statement returns "Array[4]" instead of the 4th element in
the 6th row.

Any suggestions on what I ought to be doing please to make $table a proper 2
dimensional array?

Multi-Dimensional Array
Let's say I have the following multidimensional array:

$foodtypes = array (
"Fruit" => array ("Apple", "Pear"),
"Vegetable" => array ("Lettuce", "Eggplant", "Pepper"),
"Meat" => array ("Beef", "Pork"));

Assuming that $food = 'Eggplant', How do I find what foodtype it belongs to? I know the following works, but I know there must be a better way to do this, like using array_search or array_keys. I can't get anything other the following to work though. Code:

Getting Data Out Of Three Dimensional Array
I want to extract data from 3-dimensional array into one dimensional array here's example of two arrays that i add into one: PHP Code:

Multi Dimensional Array
I want to go create a table with a textfield where the user can
enter an amount for a certain dynamically created article coming from
the database.

Later, I want to calculate the whole price and so on.
It works nicely to create my multi dimensional array,
however, it does not work to save the values coming from the form to
calculate the price.
What's wrong???

<form name="shop" method="post" action="index.php">
$articleTable = array();

while ($row = mysql_fetch_array($result)) {
$articleNr= $row["articleNr"];
$name= $row["name"];
$picName= $row["picName"];
$price = $row["price"];
$amount="";

$articleRow = array(
"articleNr" => $articleNr,
"name" => $name,
"picName" => $bildName,
"price " => $price ,
"amount" => $amount
);

array_push($articleTable , $articleRow );

}

foreach($articleTable as $article) {
?>
<input type="text" name="article[amount]" size="2" maxlength="2"
value="<? $article[amount] ?>"></td>
}

<?
}
?>
</form>

Turn Xml Into 2 Dimensional Array
Well, www.php.net seems utterly crashed. Does anyone know how to get
an XML stream and turn it into a 2 dimensional array?

Sorting A Two Dimensional Array
I have an array, thus:

Array (
[0] => Array ( [Freq] => 28 [Name] => Tomato )
[1] => Array ( [Freq] => 4 [Name] => Banana )
[2] => Array ( [Freq] => 54 [Name] => Orange )
[3] => Array ( [Freq] => 24 [Name] => Eggplant )
[4] => Array ( [Freq] => 5 [Name] => Courgette )
[5] => Array ( [Freq] => 4 [Name] => Apple )
)

I would like to be able to sort it either by the Frequency or the Name
of the fruit or vegetable.

I just can't seem to get it to work. I'm sorry - I realise that this is
probably really easy but my brain isn't working today and the examples
on php.net seem incomprehensible to me.

Returning A 2 Dimensional Array
I am trying to program a function to return a 2 dimensional array, but
it's not working. I reduced the return value to 1 dimension and
tested that to make sure that the problem wasn't elsewhere. It had no
problem when the array was 1 dimensional.

Is there something different I need to do in order to return a 2
dimensional array from a function?

2 Dimensional Array And Foreach
I have a 2-dimensional array.  so I run it through two foreach loops to get the data out.  but, i want the foreaches to run in reverse.  lets say I have an array[3,2].  right now my foreach prints [1,1] [1,2] new line [2,1][2,2] new line [3,1][3,2] and i want it to print [1,1][2,1][3,1] new line [1,2][2,2][3,2]

Sorting Multi-dimensional Array
Sorting multi-dimensional array

I have this array:

Array
(
[0] => Array
(
[account] => 263
[counter] => 1
)

[1] => Array
(
[account] => 324
[counter] => 5
)

[2] => Array
(
[account] => 972
[counter] => 3
)

[3] => Array
(
[account] => 1316
[counter] => 3
)

[4] => Array
(
[account] => 1380
[counter] => 1
)

[5] => Array
(
[account] => 1880
[counter] => 2
)
)

I need to sort by the key [counter], how can I do that?

Multi-dimensional Array For Checkbox
Can there be a multi-dimensional array for checkboxes?

Two-Dimensional Array Insertion And Print
1. return results from an Oracle query into an array. there are 3 fields and approx. 2,000 records.

2. insert the results into an array of some type, inside of a loop, obviously.

3. print the results so i can verify the query is working.

PHP Code:

Multi-Dimensional Array Question
Can you have a multi-dimensional array like this?

$Test[0]['Fname'] = "John";
$Test[0]['Lname'] = "Doe";

Or do you have to use only numbers?

Building Multi Dimensional Array
I am trying to build a multi dimensional array from an unsorted array. I have an array made up of the lines in a text file, each line is a comma seperated set of fields. The first two fields are the lines id and it's parents id; eg Line ID, Parent ID, Data

1, 1 , one
2, 2, two
3, 3, three
4, 1, four
5, 4, five
6, 1, six
7, 2, seven

I am trying to build a multi dimensional array so that the final array would look like;

-- one
---- four
------ five
---- six
-- two
---- seven

Sessions And A Multi-dimensional Array
I'm writing a shopping cart w/ Sessions and a multi-dimensional array. I am only storing product id and qty (for right now, but decided on the multi-dimensional array for expansion purposes - storing customer instructions, etc.) I have come up with two paths, but can't decide which is better.

1. storing info based on product id:
...[cart][$prod_id] = array("qty" => $qty)

This, of course would allow for easy product checks: if ([cart][$prod_id]) {...}, but unless I store the $prod_id in the prod_id array as well, I'd be forced to use foreach(array_expression as $key => $value) when displaying the cart (as I also want the product id displayed next to the product name)

2. storing info based on item number:
...[cart][] = array("id" => $prod_id, "qty" => $qty)

This makes for more code when checking if the product is already in the cart (multiple foreach statements), but should allow the cart to be displayed more easily and logical.

Counting The First Dimension Of Two Dimensional Array
I'm trying to count just the items in the first dimension of a two dimensional array.
It seems like: PHP Code:

Sorting Multi-dimensional Array
I am having trouble getting the sort function for arrays to work correctly on my multi-dimensional array.

array[0][]=&#391;'
array[1][]='bob'
array[2][]='age'

array[0][]=&#395;'
array[1][]='bill'
array[2][]='age'

I then do sort($array[0]) But only array[0][] gets sorted, the names do not follow. Does anyone see any error on my part or have a clue for me to follow to solve this?

How To Print Elemnets Of N-dimensional Array?
What is a common way to print elements of a multidimensional array? I
treid to do it in the straightforward way:
$input_list[0][0] = "Something";
print "$input_list[0][0]";
And it does not work.

The solution that I found is to use intermediate variable:
$array = $input_list[0];
print "$array[0]";
printArray( $output_list[0] );

Are there any more elegant (or just common) ways to do it?

Changing A Value Of An Element In A Two Dimensional Array
I am having a problem with array manipulation.

in my php script i am reading from a csv file.
the content of file is like this:

Convert Two-Dimensional Array To String
I'm trying to convert a two-dimensional array to a string that I can put in a database. It needs to be searchable so the serialize() function will not work. I found a script at php.net that will implode a multi-dimensional array and it works fine. The script is: Code:

Printing From A Multi-dimensional Array
I have to create a multidimensional array that data for a bank will be stored in then from that array I will print it. My boss said to first program it like i am recieving the array. Then later he will have me create the array.

Order multidimensional Array I will recieve will be arranged in and the printed like this. Code:

Multi-dimensional Array Sorting
I need some help sorting an array, same in structure as:

Array
(
    [assoc1] => Array
        (
            [key1] => value
            [key2] => value
            [key3] => value
        )

    [assoc2] => Array
        (
            [key1] => value
            [key2] => value
            [key3] => value
        ))

What I want to do is sort the array by the value in say the key2 "column". Depending on input, the value to sort by may be key3 or some other key. 

I've looked at array_multisort(), but I'm not sure how I can specify what exact column I want to sort by, without affecting the rest.

Multi-dimensional Array Not Working Correctly???
I know this is going to be something totally stupid that I just can't see. I have a two dimensional arrray. The first index is a 0 based incremented int, and the other index is either an 'l' or a 'w'. Look what's happening:

Parsing All Multi-Dimensional Array Combinations
I am trying to build a dynamic table structure with multi-dimensional arrays. The first dimension is being pulled from the databse and can be refferred to as an attribute. The second dimension is also created on the fly by db, and can be reffered to as variations. I have tried using array_walk as well as using a recursive function that allows me to step through each of the various array combinations.

For example I may have 2 attributes; Color & Size. Color has 3 variations (Red, Green, Blue). Size has 4 varitions (Small, Medium Large, X-Large). Basically I am trying to build something like this:

Color Size
Red Small
Red Medium
Red Large
Red X-Large
Green Small
Green Medium
Green Large
Green X-Large
Blue Small
Blue Medium
Blue Large
Blue X-Large

The biggest problem with this, however, is that it needs to be dynamic enough that an attribute (like sleeve length: Short sleeve - Lon sleeve, etc...) can be added without changing the code.

Sorting An Associative Multi-Dimensional Array
I would like to sort array below using the last array of a multi-dimensional array. PHP Code:

Filtering The Elements Of A Multi-dimensional Array
I would like to be able to filter every element of a multi-dimensional array
using htmlspecialchars() and to retain the structure of the array. I can't
see how to do this when I don't know how many dimensions the array has.

Adding A Entry Into A Multi-dimensional Array
I make an SQL call to a DB and gather some info. In the following case, I have 2 elements in the array (HERO_ID #1 and #2) I then want to add a third element to to the array, but I just cant seem to grasp the concept. I always seemed to have trouble grasping the concept of arrays in programming classes for some reason. Code:

How To Declare A Global Multi Dimensional Array?
i cant figure this one out... this code declares a 1d array global. however i need a multid array to be global.... global $list_U001;

since i need a maximum of only 99 arrays...i could decklare those like that and construct the variable from counter ...but i dont know how to construct a "dynamic variable"....

global $list_U001;
global $list_U002;
global $list_U003;
etc...

for(i++)

$list_U00.'$i'.[]

Selecting 1 Field From A Multi-Dimensional Array
I want to know how do I select just 1 field from a Multi-Dimensional Array.
I know how to select all the fields, by using the following format:

<?php
foreach($fields as $key => $val){
echo $val;
}

But how can I do a similar thing, but to just select 1 specific field, not all of them?

Encoding / Decoding Multi Dimensional Session Array
Can you encode and decode multi-dimensional arrays? I think encoding them works just fine using session_encode(), however, session_decode is only capable of decoding the single dimensional arrays stored in the encoded string...

Making Mysql Result Into Multi-dimensional Array
My php problem is I want to make the result of 3 tables linked through foreign keys into a 3-dimensional array that reflects their relationship without repetition and without having to call the database more three times.

I know I'm doing a couple of things wrong, one thing for instance is initializing a variable at the end of the loop to remember the previous value s that it does not repeat itself, surely there must be a more elegant way to go about this, but I'm lost and I've been stuck on this all day. Code:

Array Sort By Value
I have an array that has the following structure:

Array
(
[0] => xml_make Object
(
[name] => Alfa Romeo
[totalItems] => 270
)

[1] => xml_make Object
(
[name] => Aston Martin
[totalItems] => 7
)

[2] => xml_make Object
(
[name] => Audi
[totalItems] => 948
)

[3] => xml_make Object
(
[name] => Austin
[totalItems] => 51
)

[4] => xml_make Object
(
[name] => BMW
[totalItems] => 2235
)
}

How can I sort the array by the value in total Items?

I Need To Sort An Array
Current Case:
I have a table in a database

PRODUCTS
--------------
product_id
product_name
product_category
product_order

I am trying to create a change order script. With Up/Down links.

So I run my querry and store the data in the database. So I end up with an
array ....

RSS Array Sort
I am pulling in a few RSS feeds into my site and I need to be able to sort the array I build by the pubdate of the feeds. The resulting array looks like this:

Array
(
    [0] => Array
        (
            [title] => Title of Feed
            [link] => link of feed
            [pubdate] =>  2007-05-04 00:00:00
            [description] =>  Description
        )

    [1] => Array
        (
            [title] => Title of Feed
            [link] => link of feed
            [pubdate] =>  2007-06-04 00:00:00
            [description] =>  Description
        )

I need to be able to sort by $theitems[$i]['pubdate'], how can I do that?

Pushing Data Into A Multi-dimensional Array From Mysql Results
First, A result array I'd want to get could look like this:

$chart['chart_data'] = array (
array ( "Region A", 10,12,11,15,20,22,21,25,31,32,),
);

The first is "Region A" and the rest is just int's that I'd pull from the db, so to set it I'd do this:

$chart [ 'chart_data' ][ 0 ][ 0 ] = "Region A";

But the problem is when I want to insert the data in the while loop (like the 10,12,11,15...), I've tried array_push but it's not working, maybe it doesn't work with multi-dimensional arrays? Anyways, here.'s what I tried, the following inside the "while" to loop the mysql results with mysql_fetch_assoc:

while($r=mysql_fetch_assoc($res)) {
   
     $chart [ 'chart_data' ][ 0 ][ 0 ] = array_push($chart['chart_data'][0][0], $r['wght']);
     // the above line is where I have problems    ^^
}

What I want is on each loop to insert the fetched data inside the array so that it gives what I gave first at the top, but what I've written above doesn't work, it gives me a warning saying "first argument must be an array" which seems to be one, but anyway, anybody know how to do this?

Using A Pseudocode To Sort An Array
I want to sort an array, but the problem is that I can't use sort, rsort, asort, etc. So I want a Pseudocode to order the array.

Sort() Messed Up My Array!
I have an assosiative array with "key"s and "value"s which I get by using array_count_values() on $array.

$array is an array of numbers, for example 1, 0, 0, -5.

Here's some code:

Sort Array Without Index
I'd like to sort a multidimensional array that hasn't numerical
index, in fact it is like:

Array
(
[mobile] => Array
(
[name_str] => mobile
[relationCount_int] => 1
)

[video] => Array
(
[name_str] => video
[relationCount_int] => 2
)

[flash] => Array
(
[name_str] => flash
[relationCount_int] => 1
)

[tool] => Array
(
[name_str] => tool
[relationCount_int] => 1
)

)

And I'd like to sort, for instance for the value of
"relationCount_int", so the new order should be something like:

Array
(
[video] => Array
(
[name_str] => video
[relationCount_int] => 2
)
[mobile] => Array
(
[name_str] => mobile
[relationCount_int] => 1
)


[flash] => Array
(
[name_str] => flash
[relationCount_int] => 1
)

[tool] => Array
(
[name_str] => tool
[relationCount_int] => 1
)

)

Multidim Array Sort
I am wondering if someone can point me to the needed sort function. There are so many of
them that I simply got lost by reading their descriptions. I try to explain what I need.

I have a multidimensional array and I have a function that outputs it as a table.

$arr[0] contains an array that contains usernames
$arr[1] contains an array that contains real names
$arr[2] contains an array that contains e-mails
etc...
$arr[last] contains integers for users "levels"

My function outputs users with their datas in the columns. Each column means one user.

Now I want to sort this whole array by levels. So, all other data should be sorted
according to the pattern in levels row.

How is this thing done?


Copyright © 2005-08 www.BigResource.com, All rights reserved