How do i sort multidimension array in PHP? [duplicate] - php

This question already has answers here:
How can I sort arrays and data in PHP?
(14 answers)
Closed 5 months ago.
I have array like
Array (
[608665839] => Array ( [score] => 2 )
[1756044141] => Array ( [score] => 5 )
[523536777] => Array ( [score] => 2 )
)
and I want to sore this array by score. How can I do?

I would use uasort

I think [uasort()]1 function is helpful for sorting this array()
If multiple array then use array_[multisort()]2 functions

From PHP.net:
<?php
function order_array_num ($array, $key, $order = "ASC")
{
$tmp = array();
foreach($array as $akey => $array2)
{
$tmp[$akey] = $array2[$key];
}
if($order == "DESC")
{arsort($tmp , SORT_NUMERIC );}
else
{asort($tmp , SORT_NUMERIC );}
$tmp2 = array();
foreach($tmp as $key => $value)
{
$tmp2[$key] = $array[$key];
}
return $tmp2;
}
?>
$order = "ASC" will sort the array in an ascending order while $order = "DESC" will sort the array in a descending order.
Hope this helps.

Related

Get single column of data from mysql_query result [duplicate]

This question already has answers here:
How do I retrieve a single column from mysqli results
(5 answers)
Closed 6 months ago.
I am currently using a mysql_query with the UNION function. This is the array that I get:
Array
(
[0] => bob
[added] => bob
)
Array
(
[0] => test1
[added] => test1
)
Is there a way that I can take this array, merge it, remove the added values, place the data in numerical order and make it look like this?:
Array
(
[0] => bob
[1] => test1
)
I know somebody'll ask me what have I done so far. Honestly, I have no idea where to go from here.
array_reduce(
array_map(function($i) {
return $i[0];
}, $data),
function($result, $item) {
$result[] = $item;
return $result;
},
array()
);
or
call_user_func_array('array_merge',
array_map(function($i) {
return $i[0];
}, $data)
);
$array1=array_unique($array1);
$array2=array_unique($array2);
$result = array_merge ($array1,$array2);
When you are fetching the data you can create your array eg:
while($row = mysqli_fetch_array($result, MYSQLI_NUM){
$newArray[] = $row[0];
}
and from your current array you can do
$newArray = array();
foreach($array as $value){
$newArray = array_push($newArray,$value[0]);
}

Get PHP array value [duplicate]

This question already has answers here:
How to Flatten a Multidimensional Array?
(31 answers)
Closed 9 years ago.
I have an array like the following:
Array
(
[0] => Array
(
[0] => 1
[1] => 2
[2] => 3
)
[1] => Array
(
[0] => 3
)
[2] => Array
(
[0] => 4
)
)
Now I want each array value into one single array. How do I do it?
Thanks in advance.
// PHP >= 5.3:
function array_value_recursive($key, array $arr){
$val = array();
array_walk_recursive($arr, function($v, $k) use($key, &$val){
if($k == $key) array_push($val, $v);
});
return $val;
}
You can recursively parse the array with a function:
$multiDimArr = array(...);
function getSingleArray( $multiDimArr ) {
$singleArray = array();
foreach($multiDimArr as $row) {
if( is_array($row) ) {
getSingleArray($row); // recursive call -> row it cand be also multi dimensional
}
else {
$singleArray[] = $val;
}
}
return $singleArray;
}
I really hope this will help!!

Merge Arrays from XML feed [duplicate]

This question already has answers here:
Sorting XML with SimpleXML/XPath?
(3 answers)
Closed 9 years ago.
I am having a little trouble with an xml feed (atom). I am running a for each loop to return prices using simple xml and converting them too arrays which works fine below :-
foreach ($dc->departures->departure as $price)
{
$lowest = $price->prices->price[5]->asXML();
$lowestval = array($lowest);
print_r($lowestval);
}
Which is returning :-
Array ( [0] => 2289 )
Array ( [0] => 2207 )
Array ( [0] => 2369 )
Array ( [0] => 2229 )
My goal is to return only the lowest price, so I can display a Prices From: area. From what I understand I need to use the min() function, however this only works with one array with several values. I've tried array_merge which doesn't seem to work and just returns the same as above. I am a PHP newbie so there maybe something obvious. A kick in the correct direction would be appreciated.
Try this. Its working fine
<?php
foreach ($dc->departures->departure as $price)
{
$lowest = $price->prices->price[5]->asXML();
$lowestval[] = $lowest;
}
$min = min($lowestval);
echo $index = array_search($min, $array);
?>
$data = array();
$data[] =Array (0 => 2289 ) ;
$data[] = Array ( 0 => 2207 ) ;
$data[] = Array ( 0 => 2369 ) ;
$data[] = Array ( 0 => 2229 );
array_multisort($data);
$first = array_shift($data);
var_dump($first); // 2207
You can also use 'sort()' function to sort an array value.
Here is an example with some extra value as well merge array.
$arry1 = array(
array(5),
array(10000),
array(2289),
array(2288),
array(2207),
array(2369),
array(2229),
array(5421),
array(541)
);
$arry2 = array(
array(456789),
array(54564)
);
$arry1 = array_merge($arry1,$arry2);
sort($val);
echo '<pre>';
print_r($val);
echo '</pre>';
then you can use first element of an array as min value.
echo $arry1[0][0];

How to change array key of this array? [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
In PHP, how do you change the key of an array element?
This the array
Array
(
[0] => Array
(
[id] => 1
[due_date] => 2011-09-23
[due_amount] => 10600.00
)
[1] => Array
(
[id] => 2
[due_date] => 2011-10-23
[due_amount] => 10600.00
)
[2] => Array
(
[id] => 3
[due_date] => 2011-11-23
[due_amount] => 10600.00
)
)
how to change id to u_id in this array?
Regards
array_walk_recursive($array, 'changeIDkey');
function changeIDkey($item, &$key)
{
if ($key == 'id') $key = 'u_id';
}
PHP Manual: array_walk_recursive
EDIT
This will not work for the reason #salathe gave in the Comments below. Working on alternative.
ACTUAL ANSWER
function changeIDkey(&$value,$key)
{
if ($value === "id") $value = "u_id";
}
$new = array();
foreach ($array as $key => $value)
{
$keys = array_keys($value);
array_walk($keys,"changeIDkey");
$new[] = array_combine($keys,array_values($value));
}
var_dump($new); //verify
Where $array is your input array. Note that this will only work with your current array structure (two-dimensions, changes keys on only second dimension).
The loop iterates through the inner arrays changing "id" to "u_id" in the keys and then recombines the new keys with the old values.
foreach( $array as &$element ) {
$element['u_id'] = $element['id'];
unset( $element['id'] );
}

PHP : flatten array - fastest way? [duplicate]

This question already has answers here:
How to Flatten a Multidimensional Array?
(31 answers)
Closed 5 months ago.
Is there any fast way to flatten an array and select subkeys ('key'&'value' in this case) without running a foreach loop, or is the foreach always the fastest way?
Array
(
[0] => Array
(
[key] => string
[value] => a simple string
[cas] => 0
)
[1] => Array
(
[key] => int
[value] => 99
[cas] => 0
)
[2] => Array
(
[key] => array
[value] => Array
(
[0] => 11
[1] => 12
)
[cas] => 0
)
)
To:
Array
(
[int] => 99
[string] => a simple string
[array] => Array
(
[0] => 11
[1] => 12
)
)
Give this a shot:
$ret = array();
while ($el = each($array)) {
$ret[$el['value']['key']] = $el['value']['value'];
}
call_user_func_array("array_merge", $subarrays) can be used to "flatten" nested arrays.
What you want is something entirely different. You could use array_walk() with a callback instead to extract the data into the desired format. But no, the foreach loop is still faster. There's no array_* method to achieve your structure otherwise.
Hopefully it will help someone else, but here is a function I use to flatten arrays and make nested elements more accessible.
Usage and description here:
https://totaldev.com/flatten-multidimensional-arrays-php/
The function:
// Flatten an array of data with full-path string keys
function flat($array, $separator = '|', $prefix = '', $flattenNumericKeys = false) {
$result = [];
foreach($array as $key => $value) {
$new_key = $prefix . (empty($prefix) ? '' : $separator) . $key;
// Make sure value isn't empty
if(is_array($value)) {
if(empty($value)) $value = null;
else if(count($value) == 1 && isset($value[0]) && is_string($value[0]) && empty(trim($value[0]))) $value = null;
}
$hasStringKeys = is_array($value) && count(array_filter(array_keys($value), 'is_string')) > 0;
if(is_array($value) && ($hasStringKeys || $flattenNumericKeys)) $result = array_merge($result, flat($value, $separator, $new_key, $flattenNumericKeys));
else $result[$new_key] = $value;
}
return $result;
}
This should properly combine arrays with integer keys. If the keys are contiguous and start at zero, they will be dropped. If an integer key doesn't yet exist in the flat array, it will be kept as-is; this should mostly preserve non-contiguous arrays.
function array_flatten(/* ... */)
{
$flat = array();
array_walk_recursive(func_get_args(), function($value, $key)
{
if (array_key_exists($key, $flat))
{
if (is_int($key))
{
$flat[] = $value;
}
}
else
{
$flat[$key] = $value;
}
});
return $flat;
}
You could use !isset($key) or empty($key) instead to favor useful values.
Here's a more concise version:
function array_flatten(/* ... */)
{
$flat = array();
array_walk_recursive(func_get_args(), function($value, $key) use (&$flat)
{
$flat = array_merge($flat, array($key => $value));
});
return $flat;
}

Categories