Sort php associative array [duplicate] - php

This question already has answers here:
Sorting an associative array in PHP [duplicate]
(5 answers)
Closed 8 years ago.
I am trying to sort an array by miles.
$i = 0;
foreach($results as $key => $value)
{
echo $results['miles'][$i] . "<br />";
echo $results['postcode'][$i] . "<br />";
echo $results['id'][$i] . "<br />";
echo $results['description'][$i] . "<br />";
echo $results['title'][$i] . "<br />";
echo $results['thumbnail'][$i] . "<br />";
$i++;
}
AS you can see I'm having 6 different keys here. I want to order everything by $results['miles'] in ASCENDING order.
This is my array structure:
Array ( [miles] => Array ( [0] => 0 [1] => 0 [2] => 14 [3] => 8 [4] => 8 [5] => 0 [6] => 8 [7] => 14 ) [title] => Array ( [0] => Stunning 1 Bedroom Apartment With Concierge [1] => Big Double Inc Bills+ Balcony+Free Parking [2] => Large, Sunny Flat In Willesden [3] => Brewhouse Yard EC1V [4] => Stunning 2 Double Bed Flat - City [5] => Room To Let £575 Pm Bills Included [6] => All Bills Inclusive | Gorgeous 1 Bed In The City [7] => Large Double Room In Zone 2 (Kensal Green 2 Mins) ) [id] => Array ( [0] => 187 [1] => 176 [2] => 186 [3] => 178 [4] => 179 [5] => 177 [6] => 183 [7] => 182 ) [thumbnail] => Array ( [0] => [1] => [2] => [3] => [4] => [5] => [6] => [7] => ) [postcode] => Array ( [0] => IG11 [1] => ig11 [2] => NW10 [3] => EC1 [4] => ec1 [5] => ig11 [6] => ec1 [7] => NW10 ) )
Any help would be appreciated!

If you can, the best way is to sort the data before it comes in to your script (if it's coming from SQL then order it there).
If you need to do it in PHP though you can use the uasort function, which allows you to define your own comparison:
function compareMiles($a, $b) {
if ($a['miles'] == $b['miles']) {
return 0;
}
return ($a['miles'] < $b['miles']) ? -1 : 1;
}
uasort($results, 'compareMiles');

You can use usort() function to sort it.

Use asort() to sort an array by maintain index association.
Refer this link for details and example

Related

Accessing values from inner array [duplicate]

This question already has answers here:
How can I access an array/object?
(6 answers)
Closed 6 years ago.
Array ( [err] => [num] => 1 [result] => Array ( [0] => Array ( [0] => 85 [proj_id] => 85 [1] => Automatic Mobile Alert System For Lethal Gas Detection [proj_item_title] => Automatic Mobile Alert System For Lethal Gas Detection [2] => GSM PROJECTS [proj_category] => GSM PROJECTS [3] => 5000 [actual_price] => 5000 [4] => 4000 [discount_price] => 4000 [5] => 5 [rating] => 5 [6] => automatic-mobile-alert-system-for-lethal-gas-detection [friendly_url] => automatic-mobile-alert-system-for-lethal-gas-detection [7] => gsnrtmccfoqqkgb8qs2ni5hud36c032j [session_id] => gsnrtmccfoqqkgb8qs2ni5hud36c032j [8] => 85 [9] => 2017-01-20 [date_added] => 2017-01-20 [10] => 1 [qty] => 1 ) ) )
I need to access elements from the array "result". How can I access them. Please help me.
echo $array['result'][0][0]
Will return 85
$result = $array['result'][0]
Will give you a nice way to save the Result array into another Array.
So you can do
$result[0] //Returns 85 again
Your $data['result'] is an array so you can simply loop over the elements
foreach($data['result'] as $result) {
var_dump($result);
echo $result[0];
echo $result['proj_item_title'];
echo $result['proj_id']; //etc
}

Getting data from an object array

I have an array
Array (
[bla123] => Array
(
[0] => 2
[1] => 3
[2] => 2
[3] => 2
[4] => 2
[5] => 2
[6] => 2
[7] => 2
[8] => 2
)
[12xye] => Array
(
[0] => 4
[1] => 3
[2] => 3
[3] => 2
[4] => 2
[5] => 4
[6] => 2
[7] => 2
[8] => 2
)
)
How can i access this array in php and also get the number of 1,2,3.. etc from it in php.
The logic is to get the rating of a products. the data is fetched from the database completely and then sorted using php.
for eg:
product1
one star:1
two star:3
three star:2
etc...
somewhat like a star system in flipkart, amazons etc..
use the below code:
<?php
$mainArrDat = array('bla123'=>array('Your_Array_Data_Here'),'12xye'=>('Your_Array_Data_Here'));
foreach( $mainArrDat as $mainArr )
{
foreach($mainArr as $nowArr)
{
//you can access the data that you require from $nowArr
}
}
?>

How can i compare and merge two array

I have following two arrays which comes from the same database use the same query to get both. both contains information about a single sales order having two different line items(Bill of materials) the first one has Line ItemItemID= 600271 and the second one has LineItem ItemID=600274 but as you can see below they both have the same Sales Order Number [CustomerSONo] => [7] => **15020**
so How can i compare or union these two array's. ?
//query
$result= --select statement--;
while($row = mysqli_fetch_array($result)) {
print_r($row);
}
Array 1
Array (
[0] => XXX001
[CustomerId] => XXX001
[1] => XXX Company Name.*
[Customer_Bill_Name] => XXX Company Name.*
[2] => DHE
[WhichShipVia] => DHE [3] =>
[INV_POSOOrderNumber] => [4] => 2014-12-19
[ShipByDate] => 2014-12-19 [5] =>
[GoodThruDate] => [6] =>
[CustomerSONo] => [7] => 15020
[Reference] => 15020 [8] => 2014-11-25
[TransactionDate] => 2014-11-25 [9] => 1
[DistNumber] => 1
[10] => 70.0000000000000000000 //here is the difference 1
[Quantity] => 70.0000000000000000000 //here is the difference 2
[11] => 600271 //here is the difference 3
[ItemId] => 600271 //here is the difference 4
[12] => ASSY7.60-15SL/8 FRM I1 15X6 6-6, BLK (GWT-761508 (24) //here is the difference 5
[SalesDescription] => ASSY7.60-15SL/8 FRM I1 15X6 6-6, BLK (GWT-761508)(24)//here is the difference 1 //here is the difference 6
[13] => AS1577 //here is the difference 7
[PartNumber] => AS1577 //here is the difference 8
[14] => ASSY7.60-15 8PLY W/WHL15X6 BLK //here is the difference 9
[ItemDescription] => ASSY7.60-15 8PLY W/WHL15X6 BLK )
Array 2:
Array (
[0] => XXX001
[CustomerId] => XXX001
[1] => XXX Company Name.*
[Customer_Bill_Name] => XXX Company Name.*
[2] => DHE [WhichShipVia] => DHE [3] =>
[INV_POSOOrderNumber] => [4] => 2014-12-19
[ShipByDate] => 2014-12-19 [5] =>
[GoodThruDate] => [6] =>
[CustomerSONo] => [7] => 15020
[Reference] => 15020 [8] => 2014-11-25
[TransactionDate] => 2014-11-25 [9] => 2
[DistNumber] => 2
[10] => 6.0000000000000000000 //here is the difference 1
[Quantity] => 6.0000000000000000000 //here is the difference 2
[11] => 600274 //here is the difference 3
[ItemId] => 600274 //here is the difference 4
[12] => ASSY9.5L-15SL/8 FLT I1 15X8 6-6, BLK (GWT-951508)(16)
[SalesDescription] => ASSY9.5L-15SL/8 FLT I1 15X8 6-6, BLK (GWT-951508)(16) //here is the difference 5
[13] => AS1601 //here is the difference 6
[PartNumber] => AS1601 //here is the difference 7
[14] => ASSY9.5L-15 W/WHL15X8 6/6 BLK //here is the difference 8
[ItemDescription] => ASSY9.5L-15 W/WHL15X8 6/6 BLK ) //here is the difference 9
Option 1
$orders = array();
while($row = mysqli_fetch_array($result)) {
$orders[$row['CustomerSONo'][] = $row;
}
This will add all rows that share the same CustomerSONo together in one array. If you have multiple orders, you can get all the seperate orders using
foreach($orders as $orderNo => $order) {
foreach($order as $key => $orderRow) {
}
}
Option 2
If you however only want to extract the ItemIDs from each order, you can do the following:
$orderItems = array();
while($row = mysqli_fetch_array($result)) {
$orderItems[$row['CustomerSONo']][] = $row['ItemID'];
}
This will create an array called $orderItems that only stores the order numbers in the array, rather than all the information about the order.
Option 3
If you want to echo the lines, you first have to "sort" them like in Option 2. Once you have gained all ItemIDs that belong to one CustomerSONo, you do another foreach loop to echo them into a single line.
foreach($orders as $orderNo => $itemIds) {
echo "Order #" . $orderNo . ": " . implode(", ", $itemIds);
}
This will create the following:
Order #1: 18340, 1837, 13
Order #2: 183, 868, 285, 860

Re-order PHP array by middle key as start (Circular Sorting)

very basic question however I have had some trouble finding the answers on PHP.NET.
I have the following array:
Array (
[1] => Array
(
[1] => 4
[2] => 1
[3] => 5
[4] => 3
)
[2] => Array
(
[5] => 2
[6] => 8
[7] => 7
[8] => 6
)
[3] => Array
(
[9] => 10
[10] => 9
[11] => 12
[12] => 11
)
[4] => Array
(
[13] => 15
[14] => 16
[15] => 14
[16] => 13
)
)
I want the array to be re-ordered so that the key number 3 in the first series of the array becomes the first, then the rest to be re-ordered from there to eventually get the result of:
Array (
[3] => Array
(
[9] => 10
[10] => 9
[11] => 12
[12] => 11
)
[4] => Array
(
[13] => 15
[14] => 16
[15] => 14
[16] => 13
)
[1] => Array
(
[1] => 4
[2] => 1
[3] => 5
[4] => 3
)
[2] => Array
(
[5] => 2
[6] => 8
[7] => 7
[8] => 6
)
)
I am looking for a way to do this so I can define the array, then the first level key I need to sort by, and then it will return the array in this way.
The standard PHP keys didn't seem to offer something like this, so it would be good to be able to have a separate function such as $newArray = reorder_array($array, $key);
I don't require any sorting of the second level, only the initial 4 main / first level array sections.
You help is greatly appreciated as I have been sitting on this one for awhile without a clear and simple solution.
You re-ordering can be simply implemented with one foreach loop, like:
function reorderArray($array, $key)
{
$found = false;
foreach($array as $k=>$v)
{
$found = $found || $k===$key;
if(!$found)
{
unset($array[$k]);
$array[$k] = $v;
}
//else break can be added for performance issues
}
return $array;
}
with usage
$array=[1=>'foo', 4=>'bar', 9=>'baz', 'test'=>51];
var_dump(reorderArray($array, 9));
var_dump(reorderArray($array, 'test'));
var_dump(reorderArray($array, 'no_such_key'));//original array in result
-check this demo. If keys are consecutive numerics, however, this can be easily implemented with array_slice() calls.

Iterate through array and get key and value [duplicate]

This question already has answers here:
How to loop through an associative array and get the key?
(12 answers)
Closed 8 years ago.
I need to iterate through a dynamic array. The array will look something like the following:
Array
(
[2010091907] => Array
(
[home] => Array
(
[score] => Array
(
[1] => 7
[2] => 17
[3] => 10
[4] => 7
[5] => 0
[T] => 41
)
[abbr] => ATL
[to] => 2
)
[away] => Array
(
[score] => Array
(
[1] => 0
[2] => 7
[3] => 0
[4] => 0
[5] => 0
[T] => 7
)
[abbr] => ARZ
[to] => 2
)
[weather] =>
[media] => Array
(
[tv] => FOX
[sat] => 709
[sathd] => 709
[radio] => Array
(
[home] => 153
[away] => 90
)
)
[bp] => 13
[yl] =>
[qtr] => Final
[down] => 0
[togo] => 0
[clock] => 00:26
[posteam] => ARZ
[note] =>
[redzone] =>
[stadium] => Georgia Dome
)
I need it to be dynamic and for testing purposes, I need to be able to call it via:
echo "Key: $key; Value: $value<br />\n";
I'm going to later take this information and place it into a mysql database, but for now, I need to brush up on arrays and figure out how to format the data.
Any help is appreciated.
I´d go for a recursive function: If a value is an array, call it again and otherwise display the key / value pair.
Something like (not tested):
function display_array($your_array)
{
foreach ($your_array as $key => $value)
{
if is_array($value)
{
display_array($value);
}
else
{
echo "Key: $key; Value: $value<br />\n";
}
}
}
display_array($some_array);

Categories