How to sort an multidimensional array using Php? [duplicate] - php

This question already has answers here:
How to Sort a Multi-dimensional Array by Value
(16 answers)
Closed 6 years ago.
I have an multidimensional array and want to sort in according to date and also want to get only 5 data from an array.
Array :
Array
(
[0] => Array
(
[ID] => 1
[TITLE] => example1
[DATE] => 2016-05-17
[PST_BY] => 0
[IMG_NM] =>
[SLUG] =>
[NAME] => Web Design & Development
)
[1] => Array
(
[ID] => 2
[TITLE] => example2
[DATE] => 2016-05-20
[PST_BY] => 0
[IMG_NM] =>
[SLUG] =>
[NAME] => Mobile OS
)
)
I am doing this but not working :
$list = array_sort($blog, 'DATE', SORT_ASC);
print_r($list);

Example to sort on a specific key (in this case name):
// Function to compare two items in the array
function CompareName($left, $right) {
return $left['name'] > $right['name'];
}
// Example array/data
$myarray = [
["id"=>1, "name"=>"foo"],
["id"=>2, "name"=>"bar"],
["id"=>3, "name"=>"ah"],
["id"=>4, "name"=>"zoo"]
];
echo 'Unsorted:';
var_dump($myarray);
usort($myarray , 'CompareName');
echo 'Sorted:';
var_dump($myarray);
want to get only 5 data from an array
$top5 = array_slice($myarray, 0, 5);
or:
$top5 = array_splice($myarray, 0, 5);

Related

Create a multidimensional array based on number of values [duplicate]

This question already has answers here:
Transpose a PHP multidimensional array with predefined keys
(3 answers)
How to transpose a multidimensional multi-file upload submission and maintain associative keys?
(4 answers)
Closed 1 year ago.
i have an array that i get from a form with alot of fields, i need to order those fields under an array and that array under the ''main'' array. Ill post what i have, and what i need to get.
WHAT I HAVE:
Array
(
[perfil_area1] => Array
(
[0] => a2
[1] => a3
)
[perfil_years] => Array
(
[0] => 2
[1] => 4
)
[perfil_function] => Array
(
[0] => f1
[1] => f4
)
[perfil_obs] => Array
(
[0] => teste1
[1] => teste2
)
[perfil_company] => Array
(
[0] => emp1
[1] => emp2
)
)
This is what i need to be so i can turn it into a query:
What i need
Array
(
[0] =>
(
[perfil_area1] => a2
[perfil_years] => 2
[perfil_function] => f1
[perfil_obs] => teste1
[perfil_company] => emp1
)
[1] =>
(
[perfil_area1] => emp2
[perfil_years] => 2
[perfil_function] => f4
[perfil_obs] => 4
[perfil_company] => a3
)
)
i have tried with 2 foreach but i didnt manage to get it done. I have read Create a multidimensional array in a loop , how to create multidimensional array using a foreach loop in php? , create multidimensional array using a foreach loop , Converting an array from one to multi-dimensional based on parent ID values and some more but i still cant do it. Any tips on how to create it?
You just need to loop over the input array and build the new array
$new = [];
foreach ($in as $key=>$arr) {
$new[0][$key] = $arr[0];
$new[1][$key] = $arr[1];
}
<?php
$result = [];
for ($i=0; $i<count(reset($array)); $i++) {
$result[] = array_combine(array_keys($array), array_column($array, $i));
}
Please read the manual for more details about array_combine(), array_keys() and array_column().

How to combine multiple arrays into one in PHP [duplicate]

This question already has answers here:
PHP: merge two arrays while keeping keys instead of reindexing?
(6 answers)
Closed 4 years ago.
I have a multiple arrays which I'd like to put into a single array in order to sort it:
$weight = array($weight);
$dev = array_combine($missing, $weight);
echo "<pre>";
print_r($dev);
echo "</pre>";
Output:
Array (
[angular] => 2
)
Array (
[android sdk] => 3
) Array (
[application] => 1
)
Now how do I turn the array above into this?
Array (
[android sdk] => 3
[angular] => 2
[application] => 1 )
I've tried the below from a solution that I've found on this site, but it returns NULL:
$weight = array($weight);
$dev = array_combine($missing, $weight);
$result = call_user_func_array("array_merge", $dev);
echo "<pre>";
print_r($result);
echo "</pre>";
EDIT
Here is my $missing array, some arrays are empty because a match hasn't been found against some keywords:
Array
(
)
Array
(
[0] => angular
)
Array
(
[0] => android sdk
)
Array
(
[0] => application
)
Array
(
)
Here are the value from $weight:
3 2 3 1 3
How can I get this?
Array (
[android sdk] => 3
[angular] => 2
[application] => 1 )
use array_merge:
$array1 = [1,2,3];
$array2 = [4,5,6];
$result = array_merge($array1, $array2);
print_r($result);
results in:
Array
(
[0] => 1
[1] => 2
[2] => 3
[3] => 4
[4] => 5
[5] => 6
)
You can use array_merge function.
Therefore, the code will be
array_merge($array1, $array2);

Multiple arrays merging issue [duplicate]

This question already has answers here:
Merge two arrays as key value pairs in PHP
(3 answers)
Closed 5 years ago.
I have two arrays
First array
array(
[0] => +970
[1] => +971
[2] => +972
)
And Second array
array(
[0] => 465465454
[1] => 321321355
[2] => 987946546
)
I want to merge them like this
array(
[+970] => 465465454
[+971] => 321321355
[+972] => 987946546
)
I try with array_merge but this gives me the result that I didn't want e.g.
$busi_code = $page1_data->business_code; //array
$busi_num = $page1_data->business_number; //array
$business_phone_numbers = array_merge($busi_code, $busi_num);
echo '<pre>';
print_r($business_phone_numbers);
echo '</pre>';
And its result is
[0] => +970
[1] => +971
[2] => +972
[3] => 465465454
[4] => 321321355
[5] => 987946546
So please guide me how can I achieve my required result.
You're looking for array_combine, rather than array_merge:
Creates an array by using the values from the keys array as keys and the values from the values array as the corresponding values.
$business_phone_numbers = array_combine($busi_code, $busi_num);
See https://eval.in/954799
This is job for array_combine function:
$business_phone_numbers = array_combine($busi_code, $busi_num);
DOCS: http://php.net/manual/en/function.array-combine.php
You must use array_combine.
Try this:
$a = array(
0 => +970,
1 => +971,
2 => +972);
$b = array(
0 => 465465454,
1 => 321321355,
2 => 987946546);
$r = array_combine($a,$b);
print_r($r);

How to sort multidimensional array by name/timestamp? [duplicate]

This question already has answers here:
How can I sort arrays and data in PHP?
(14 answers)
Closed 5 years ago.
I were using the "rsort" function to sort through the timestamps when the array only contained a timestamp and were not multidimensional.
So now the question is how do i approach this?
The array looks something similair to this
Array
(
[0] => Array
(
[type] => post
[id] => 1
[timestamp] => 2017-08-12 21:03:22
[poster] => 1
[profile] => 1
[post] => Testtttttinngggs
)
[1] => Array
(
[type] => post
[id] => 2
[timestamp] => 2017-08-12 21:03:18
[poster] => 1
[profile] => 5
[post] => Hello you
)
[2] => Array
(
[type] => post
[id] => 3
[timestamp] => 2017-08-12 21:03:33
[poster] => 1
[profile] => 1
[post] => Somesay timestamp is screwed
)
[3] => Array
(
[type] => post
[id] => 4
[timestamp] => 2017-08-12 21:28:54
[poster] => 1
[profile] => 1
[post] => This is truely a teeest
)
[4] => Array
(
[type] => post
[id] => 5
[timestamp] => 2017-08-13 15:04:34
[poster] => 1
[profile] => 1
[post] => Test test test test
)
)
You can use array_multisort
array_multisort(array_column($list, 'timestamp'), SORT_ASC, $list);
You can use usort
usort($array, function($a, $b)
{
if($a['timestamp']>$b['timestamp'])
{
return -1;
}
elseif($a['timestamp']<$b['timestamp'])
{
return 1;
}
return 0;
});
Update
I was wrong. Axalix' answer runs a lot faster than mine and Rob Ruchte's. My tests:
$data = [
['timestamp'=> '2015-08-12', 'id'=>1],
['timestamp'=> '2017-07-13', 'id'=>2],
['timestamp'=> '2017-01-12', 'id'=>3],
];
function useUsort($data){
usort($data,function($a,$b) {
return strtotime($b['timestamp']) - strtotime($a['timestamp']);
});
};
function useMultisort($data){
array_multisort(array_column($data, 'timestamp'), SORT_DESC, $data);
};
$start = microtime(true);
for($i=1;$i<=100000;$i++) useUsort($data);
$t1 = microtime(true);
for($i=1;$i<=100000;$i++) useMultisort($data);
$t2 = microtime(true);
echo "usort: ". round(($t1 - $start) * 1000) . " ms\n";
echo "array_multisort: ". round(($t2 - $t1) * 1000) . " ms\n";
My result:
usort: 2262 ms
array_multisort: 246 ms
Original answer
#Axalix' answer is nice but I would take a different approach. Because you only care about sorting by one field (timestamp), array_multisort is overkill as it was design to sort by multiple fields. I would do:
usort($data,function($a,$b) {
return strtotime($b['timestamp']) - strtotime($a['timestamp']);
});
Live demo
This will easily outperform array_multisort because it doesn't require PHP to first extract the timestamp into a separate column array, and then execute the multisort (a more complex function than my simple comparator function) on it.

PHP multi dimensional arrays [duplicate]

This question already has answers here:
How can I sort arrays and data in PHP?
(14 answers)
Closed 8 years ago.
I have two questions.
How can i create an array which i can add two values per index like:
$sample[0] = ("abc",10);
Second is that once i have created this array i would like to sort this array according to the 2nd value at the index.
So if i have an array like:
$sample[0] = ("abc",32);
$sample[1] = ("def",11);
The sorted result should be:
$sample[0] = ("def",11);
$sample[1] = ("abc",32);
Answer to part one:
$sample[0] = array("abc", 10);
Answer to part two:
array_multisort($sample, SORT_NUMERIC);
Testing Environment:
<?php
$sample[0] = array("abc", 32);
$sample[1] = array("def", 11);
print_r($sample);
array_multisort($sample, SORT_NUMERIC);
echo '<br />';
print_r($sample);
?>
Output:
Array ( [0] => Array ( [0] => abc [1] => 32 ) [1] => Array ( [0] => def [1] => 11 ) )
Array ( [0] => Array ( [0] => def [1] => 11 ) [1] => Array ( [0] => abc [1] => 32 ) )
Warning from #Deceze:
Above functionality is coincidental; correct code is:
usort($sample, function ($a, $b) { return $a[1] - $b[1]; })

Categories