This question already has answers here:
How can I sort arrays and data in PHP?
(14 answers)
Closed 8 years ago.
I have an array named as $result which have contents something like this:
Array (
[1114_435] => stdClass Object
(
[uid] => 435
[v_first_name] => fHerter
[v_last_name] => Herter
[id] => 1114
[v_title] => Morning Stretch
[fk_resident_id] => 435
[v_location] => Front Lawn
[i_started_date] => 1357054200
)
[1114_444] => stdClass Object
(
[uid] => 444
[v_first_name] => fXYZ
[v_last_name] => XYZ
[id] => 1114
[v_title] => Morning Stretch
[fk_resident_id] => 444
[v_location] => Front Lawn
[i_started_date] => 1357054200
)
[1114_448] => stdClass Object
(
[uid] => 448
[v_first_name] => fDavidson
[v_last_name] => Davidson
[id] => 1114
[v_title] => Dinner
[fk_resident_id] => 448
[v_location] => Front Lawn
[i_started_date] => 1357051000
)
)
I want to sort it on the basis of i_started_date. I tried using ksort, asort etc but no luck, maybe i wasn`t using it properly. Any help would be highly appreciated.
Thanks!
Try something like this:
function sortArray($data)
{
$sortArray = array();
foreach($data as $dt)
{
foreach($dt as $key=>$value)
{
if(!isset($sortArray[$key]))
{
$sortArray[$key] = array();
}
$sortArray[$key][] = $value;
}
}
$orderby = "1"; //change this to whatever key you want from the array
array_multisort($sortArray[$orderby],SORT_ASC,$data);
return $data;
}
Related
This question already has answers here:
Loop through a two-dimensional array
(6 answers)
Closed 2 years ago.
How do I iterate list of dictionary returned from curl response in PHP?
Here is structure of a returned response:
Array (
[0] => Array (
[status] => open
[serviceSpecification] => https://testdomain.com
[expirationDate] =>
[name] => abcd.com
[service] => servicekey
[domainName] => domainname
[productInstanceUrl] => https://anotherinstanceurl.com
[createDate] => 2019-04-15
[serviceSpecificationTextKey] => test.core.key
[billingCycle] => 1
)
[1] => Array (
[status] => open
[serviceSpecification] => https://test.net
[expirationDate] =>
[name] => testname
[service] => https://service.com
[domainName] => test
[productInstanceUrl] => https://instanceurl.com
[createDate] => 2019-04-15
[serviceSpecificationTextKey] => core.test.key
[billingCycle] => 1
)
)
I tried doing following but not working:
foreach ($aboveVariable as $record) {
echo $record['domainName'];
}
Note: I believe its more of a how to iterate through list of list in PHP?
To just show the domainName for each then the code you show works. But based on this I believe its more of a how to iterate through list of list in PHP? I would say you just want to loop the main array and then the sub-arrays:
foreach($aboveVariable as $record) {
foreach($record as $name => $value) {
echo "$name = $value<br>\n";
}
echo "<br>\n";
}
Will show something like:
status = open
serviceSpecification = https://testdomain.com
etc...
status = open
serviceSpecification = https://test.net
etc...
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.
I have JSON API response which look something like this
Array
(
[sections] => Array
(
[0] => Array
(
[id] => 115000089967
[url] => xxxxx
[html_url] => ArticleHTML1
[category_id] => 204458828
[position] => 0
[sorting] => manual
[created_at] => 2016-12-19T14:56:23Z
[updated_at] => 2017-02-03T08:23:04Z
[name] => ArticleName1
[description] =>
[outdated] =>
)
[1] => Array
(
[id] => 207077828
[url] => xxxxxx
[html_url] => ArticleHTML2
[category_id] => 204458828
[position] => 1
[sorting] => manual
[created_at] => 2016-11-14T09:28:30Z
[updated_at] => 2017-02-02T09:15:42Z
[name] => ArticleName2
[description] =>
[outdated] =>
)
)
[page] => 1
[per_page] => 30
[page_count] => 1
[sort_by] => position
[sort_order] => asc
)
I have successfully iterated this with foreach, so return looks like this:
ArticleName1 ArticleHTML1
ArticleName2 ArticleHTML2
So I took [name] and [html_url] from each like this:
$details1 = array('name');
$details2 = array('html_url');
foreach($sections['sections'] as $article) {
foreach($details1 as $detail) {
echo "$article[$detail] ";
}
foreach($details2 as $detail) {
echo "$article[$detail]\n";
}
}
But what I want next is that, that response should be exploded to one single array like this:
Array
(
[0] => ArticleName1 ArticleHTML1
[1] => ArticleName2 ArticleHTML2
)
I already managed to explode those to individual arrays:
foreach($sections['sections'] as $article) {
foreach($details1 as $detail) {
$name = "$article[$detail] ";
}
foreach($details2 as $detail) {
$url = "$article[$detail]\n";
}
$string = $name . $url;
$array = explode(' ', $string, 1);
print_r($array);
}
but I need just one array.
How? I'm lost or just doesn't understand, am I even close?
EDIT
The thing here is that the JSON dump is pretty large and I only need few things (name and url). So I was thinking that I first grab the whole thing, then I just take the names and urls (like the first foreach is doing), and then put those back to array. Because from those names and urls I need only last 12 keys, and taking those from sinlge array would be easy.
Tho it would be perfect, if I could sort out the keys which I don't want, in the first place. That would solve my problem. Then I wouldn't need a new array etc.
You're making this much more difficult than it needs to be. It's just a single loop:
$array = array();
foreach ($sections['sections'] as $article) {
$array[] = $article['name'] . ' ' . $article['html_url'];
}
This question already has answers here:
How can I sort arrays and data in PHP?
(14 answers)
Sort array of objects by one property
(23 answers)
Closed 8 years ago.
I trust you are well.
I would like to try and sort this array by the score property of the object. Below is an example of the data (print_r).
Array
(
[0] => stdClass Object
(
[device] => 352454530452548
[reg] => MAM 432A
[distance] => 823.36
[ha_points] => 1
[hb_points] => 235
[hc_points] => 7.5
[idling_points] => 111.5
[speeding_points] => 168
[total] => 523
[score] => 68.239895064127
)
[1] => stdClass Object
(
[device] => 3518020541565265
[reg] => SM** ***
[distance] => 851.07
[ha_points] => 14
[hb_points] => 136
[hc_points] => 6
[idling_points] => 50
[speeding_points] => 336
[total] => 542
[score] => 68.957730856451
)
The score can be anything from 0 to 100 and I would like to sort them into descending order (biggest first?). To make things more complicated, although the chances are very slim it is possible to have two identical scores in which case it doesn't matter which one is first.
Any ideas?
Thanks in advance,
Paul
A simple usort will do the job.
$arrData = array(/* ... */);
usort($arrData, function($a, $b) {
return $a->score < $b->score ? 1 : -1;
});
the print_r($a)'s result is
views_handle_field_node Object
(
[view]=>view Object
(
[db_table] => views_view
[base_table] => node
[args] => Array
(
[0] => My entry 1
)
[use_ajax] =>
[result] => Array
(
[0] => stdClass Object
(
[nid] => 5
[node_title] => Title of a test entry
[node_revisions_body] =>
[node_revisions_format] => 1
[node_vid] => 5
[term_data_name] => My first test term name
[term_data_vid] => 1
[term_data_tid] => 1
[vocabulary_name] => Vocabulary 1
[node_revisions_vid] => 5
)
[1]=> stdClass Object
(
[nid] => 8
[node_title] => Title of a test entry
[node_revisions_body] =>
[node_revisions_format] => 1
[node_vid] => 5
[term_data_name] => My first test term name
[term_data_vid] => 1
[term_data_tid] => 1
[vocabulary_name] => Vocabulary 1
[node_revisions_vid] => 5
..
[2]..
..
how to use one variable's name to out put the [nid]=>5 and[nid]=>8.....and all the nid.i use this, but can't work.
$views_handle_field_node->$view->$result[]->nid
The variables name is $a not `$views_handle_field_node' so try:
$first = $a->view->result[0]->nid;
//access all of the results?
foreach ($a->view->result as $obj) {
//do something with $obj->nid;
}
If that doesn't help then tell us what is the context? Are you putting this code inside a module hook or a template file? I that case what type of view settings. Tell us the "Style" and "Row style".
$first = $views_handle_field_node->view->result[0]->nid;
//access all of the results?
foreach ($views_handle_field_node->view->result as $obj) {
//do something with $obj->nid;
}