This question already has answers here:
How to Sort a Multi-dimensional Array by Value
(16 answers)
How can I sort arrays and data in PHP?
(14 answers)
Closed 9 years ago.
My array:
array(n) {
[...],
[100]=>
array(4) {
[0]=>
array(15) {
["TIME_PAIR"]=>
string(11) "16:35"
}
[1]=>
array(15) {
["TIME_PAIR"]=>
string(11) "11:25"
}
[2]=>
array(15) {
["TIME_PAIR"]=>
string(11) "13:25"
}
[3]=>
array(15) {
["TIME_PAIR"]=>
string(11) "15:00"
}
}
[...]
}
I need to sort arrays in array(n)[100] by "TIME_PAIR" value. Som array[100][0] should be at the end. How to do such sort? Ive tried to use array_multisort but it always doesn't work for me(
Hi you can use usort PHP function to sort your array below is the complete Code.
$arr = array(
"100"=>array(
array("TIME_PAIR"=>"16:35"),
array("TIME_PAIR"=>"11:25"),
array("TIME_PAIR"=>"13:25"),
array("TIME_PAIR"=>"15:00"),
)
);
echo "<pre>";
print_r($arr);
echo "</pre>";
function cmp($a, $b) {
return $a['TIME_PAIR'] - $b['TIME_PAIR'];
}
$res = usort($arr[100],"cmp");
echo "<pre>";
print_r($arr);
echo "</pre>";
You will have the result below..
Array
(
[100] => Array
(
[0] => Array
(
[TIME_PAIR] => 11:25
)
[1] => Array
(
[TIME_PAIR] => 13:25
)
[2] => Array
(
[TIME_PAIR] => 15:00
)
[3] => Array
(
[TIME_PAIR] => 16:35
)
)
)
Feel free to ask any questions... :)
Related
For example
[Nationality_1] string(8)=>Indian [Nationality_5] string(12)=>American [Nationality_12] string(17)=>Japanese
I got these array values by foreach loop but I want to put these value to single array by index on strings
Desired output
[Nationality] [0] string(8)=>Indian [1] string(12)=>American[2]string(17)=>Japanese
I have tried array_values but output Null
I tried this but creates duplicate array in loop for multiple orders Please help me on it . Thanks
$Nationality[] = $value;
One solution is below code:
$nationality = array(
'Nationality_1' => 'Indian',
'Nationality_2' => 'American',
'Nationality_3' => 'Japanese'
);
$temp = array();
foreach ($nationality as $val) {
$temp[] = $val;
}
$nationality = $temp;
print_r($nationality);
unset($temp);
// Array ( [0] => Indian [1] => American [2] => Japanese )
It sounds like you may want to use array_values to pull all the nationalities from your input list.
array_values
Return all the values of an array
http://php.net/array_values
What you do with that is then up to you but from your desired output it seems you want them under another array with a "Nationality" key?
Here is an example...
$input = array(
'Nationality_1' => 'Indian',
'Nationality_5' => 'American',
'Nationality_12' => 'Japanese'
);
$output = array('Nationality' => array_values($input));
var_dump($output);
/*
array(1) {
["Nationality"]=>
array(3) {
[0]=>
string(6) "Indian"
[1]=>
string(8) "American"
[2]=>
string(8) "Japanese"
}
}
*/
See the code in action: https://eval.in/869938
This question already has answers here:
How to Flatten a Multidimensional Array?
(31 answers)
Closed 2 years ago.
I'm looking to find a way to merge all child arrays into one large array.
array (
[0] =
[0] = '0ARRAY',
[1] = '1ARRAY'
[1] =
[0] = '2ARRAY',
[1] = '3ARRAY'
)
into
array (
[0] = '0ARRAY', [1] = '1ARRAY', [2] = '2ARRAY', [3] = '3ARRAY'
)
Without using array_merge($array[0],$array[1]) because I don't know how many arrays there actually are. So I wouldn't be able to specify them.
Thanks
If I understood your question:
php 5.6+
$array = array(
array('first', 'second'),
array('next', 'more')
);
$newArray = array_merge(...$array);
Outputs:
array(4) { [0]=> string(5) "first" [1]=> string(6) "second" [2]=> string(4) "next" [3]=> string(4) "more" }
Example: http://3v4l.org/KA5J1#v560
php < 5.6
$newArray = call_user_func_array('array_merge', $array);
If it's only two levels of array, you can use
$result = call_user_func_array('array_merge', $array);
which should work as long as $array isn't completely empty
$new_array = array();
foreach($main_array as $ma){
if(!empty($ma)){
foreach($ma as $a){
array_push($new_array, $a);
}
}
}
You can try it by placing these values:
$main_array[0][0] = '1';
$main_array[0][1] = '2';
$main_array[1][0] = '3';
$main_array[1][1] = '4';
OUTPUT:
Array ( [0] => 1 [1] => 2 [2] => 3 [3] => 4 )
This question already has answers here:
How to remove duplicate values from a multi-dimensional array in PHP
(18 answers)
How to remove duplicate values from an array in PHP
(27 answers)
Closed 9 years ago.
First i will like to say that, i have looked into other post but failed trying to accomplish my needs. I have used array_unique($array) but the duplicates don't get discarded. This is a view of my array using var_dump:
{
[0]=>
string(12) "44.94.192.40"
}
array(1) {
[0]=>
string(12) "44.94.192.41"
}
array(1) {
[0]=>
string(9) "44.94.1.1"
}
array(1) {
[0]=>
string(9) "44.94.1.1"
}
array(1) {
[0]=>
string(13) "44.96.253.100"
}
"44.94.1.1" is a duplicate which i hope to remove but i can't. Does this have to do with my array structure ?
Edited in response to your comment:
From the documentation on array_unique():
Two elements are considered equal if and only if (string) $elem1 === (string) $elem2. In words: when the string representation is the same.
So the fact that each of your values is an array is interfering.
Try creating an array containing just the string values:
$new_array = array();
foreach ($array as $value) {
$new_array[] = $value[0];
}
$new_array = array_unique($new_array);
You can flatten your array and do array unique or do array_map with a reference to a foreign array
<?php
$data = array(
array("44.94.192.40"),
array("44.94.192.41"),
array("44.94.1.1"),
array("44.94.1.1"),
array("44.96.253.100"),
);
$visited = array();
array_map(function($v) use ( &$visited ){
if(array_search( $v[0], $visited ) === false){
$visited[] = $v[0];
};
},$data);
var_dump($visited);
array(4) {
[0]=>
string(12) "44.94.192.40"
[1]=>
string(12) "44.94.192.41"
[2]=>
string(9) "44.94.1.1"
[3]=>
string(13) "44.96.253.100"
}
You can find a variety of ways to remove duplicates from a multidimensional array on the php doc page of array_unique in the user comments
http://us3.php.net/array_unique
Orel also mentioned a duplicate question that at a glance also contains a function for doing the same
How to remove duplicate values from an array in PHP
For simplicity I have picked one for you, but depending on exactly what you want, there are many different flavors on the php page I linked
foreach ($arrAddressList AS $key => $arrAddress) {
$arrAddressList[$key] = serialize($arrAddress);
}
$arrAddressList = array_unique($arrAdressList);
foreach ($arrAddressList AS $key => $strAddress) {
$arrAddressList[$key] = unserialize($strAddress);
}
You can do it with a foreach loop
$array = array(
array("44.94.192.40"),
array("44.94.192.41"),
array("44.94.1.1"),
array("44.94.1.1"),
array("44.96.253.100"),
);
$temp_arr=array();
foreach($array as $elementKey => $element)
{
foreach($element as $valueKey => $value)
{
if(in_array($value,$temp_arr)) unset($array[$elementKey]);
else $temp_arr[]=$value;
}
}
print_r($array);
Output would be:
Array ( [0] => Array ( [0] => 44.94.192.40 ) [1] => Array ( [0] => 44.94.192.41 ) [2] => Array ( [0] => 44.94.1.1 ) [4] => Array ( [0] => 44.96.253.100 ) )
I'm trying to find a way to sort my array from SimpleXMLElement. I'd like to sort by start time which I can get from event_start_dt. I'd also like to sort by room ID as a separate process. Currently the array is in order by object(SimpleXMLElement) #. Here is the var_dump($array):
object(SimpleXMLElement)#275 (1) {
["reservation"]=> array(3)
{
[0]=> object(SimpleXMLElement)#287 (28) {
["reservation_id"]=> string(7) "8644894"
["event_start_dt"]=> string(25) "2013-12-02T12:00:00-08:00"
["event_end_dt"]=> string(25) "2013-12-02T13:00:00-08:00"
["event_id"]=> string(6) "314147"
["event_name"]=> string(24) "Practice"
["room_id"]=> string(3) "202"
}
[1]=> object(SimpleXMLElement)#288 (28) {
["reservation_id"]=> string(7) "8595185"
["event_start_dt"]=> string(25) "2013-12-02T08:00:00-08:00"
["event_end_dt"]=> string(25) "2013-12-02T09:00:00-08:00"
["event_id"]=> string(6) "314005"
["event_name"]=> string(24) "Meeting"
["room_id"]=> string(3) "207"
}
[2]=> object(SimpleXMLElement)#289 (28) {
["reservation_id"]=> string(7) "8718654"
["event_start_dt"]=> string(25) "2013-12-02T10:00:00-08:00"
["event_end_dt"]=> string(25) "2013-12-02T11:00:00-08:00"
["event_id"]=> string(6) "315811"
["event_name"]=> string(20) "Maintenance"
["room_id"]=> string(3) "202"
}
} }
I've tried usort and asort but haven't gotten it to work with either method.
usort method:
function sortByTime($a, $b){
$a = strtotime($array->event_start_dt);
$b = strtotime($array->event_start_dt);
if ($a==$b) return 0;
return ($a < $b) ?-1 : 1;
}
usort($arrTimes, 'sortByTime');
var_dump($arrTimes);
Trying the code below gives me warning: usort() expects parameter 1 to be array, object given.
foreach ($rez->reservation as $value){
$var1 = $value->space_reservation->space_name;
$var2 = substr($value->event_start_dt,11,5);
}
sort_obj_arr($value,$var1,SORT_DESC);
echo "<pre>SORTED ";
print_r($value);
echo "</pre>";
function sort_obj_arr(& $arr, $sort_field, $sort_direction)
{
$sort_func = function($obj_1, $obj_2) use ($sort_field, &$sort_direction)
{
if ($sort_direction == SORT_ASC) {
return strnatcasecmp($obj_1->$sort_field, $obj_2->$sort_field);
} else {
return strnatcasecmp($obj_2->$sort_field, $obj_1->$sort_field);
}
};
usort($arr, $sort_func);
}
I have an array from my controler but cannot get usort working:
I get either: usort() expects parameter 1 to be array, object given or null.
$array = array($this->data);
print_r($array);
array(1) {
[0]=> object(SimpleXMLElement)#280 (1) { ["reservation"]=> array(3) {
[0]=> object(SimpleXMLElement)#287 (28) {
["reservation_id"]=> string(7) "8644894"
["event_start_dt"]=> string(25) "2013-12-02T12:00:00-08:00"
["event_end_dt"]=> string(25) "2013-12-02T13:00:00-08:00"
["event_id"]=> string(6) "314147"
["event_name"]=> string(24) "Practice"
["room_id"]=> string(3) "202"
}
[1]=> object(SimpleXMLElement)#288 (28) {
["reservation_id"]=> string(7) "8595185"
["event_start_dt"]=> string(25) "2013-12-02T08:00:00-08:00"
["event_end_dt"]=> string(25) "2013-12-02T09:00:00-08:00"
["event_id"]=> string(6) "314005"
["event_name"]=> string(24) "Meeting"
["room_id"]=> string(3) "207"
}
[2]=> object(SimpleXMLElement)#289 (28) {
["reservation_id"]=> string(7) "8718654"
["event_start_dt"]=> string(25) "2013-12-02T10:00:00-08:00"
["event_end_dt"]=> string(25) "2013-12-02T11:00:00-08:00"
["event_id"]=> string(6) "315811"
["event_name"]=> string(20) "Maintenance"
["room_id"]=> string(3) "202"
}
} }
Request for print_r:
SimpleXMLElement Object
(
[reservation] => Array(3)
(
[0] => SimpleXMLElement Object
(
[reservation_id] => 8604174
[event_start_dt] => 2013-12-31T06:00:00-08:00
[event_end_dt] => 2013-12-31T08:00:00-08:00
[event_id] => 314147
[event_name] => Practice
[room_id] => 202
)
[1] => SimpleXMLElement Object
(
[reservation_id] => 8604177
[event_start_dt] => 2013-12-31T05:00:00-08:00
[event_end_dt] => 2013-12-31T06:00:00-08:00
[event_id] => 314150
[event_name] => Meeting
[room_id] => 216
)
[2] => SimpleXMLElement Object
(
[reservation_id] => 8604189
[event_start_dt] => 2013-12-31T10:00:00-08:00
[event_end_dt] => 2013-12-31T11:00:00-08:00
[event_id] => 314150
[event_name] => Maintenance
[room_id] => 220
)
)
)
$arrTimes = xml2array($array->reservation);
var_dump($arrTimes)
array(5) {
["reservation_id"]=> string(7) "8604175"
["event_start_dt"]=> string(25) "2014-01-02T06:00:00-08:00"
["event_end_dt"]=> string(25) "2014-01-02T08:00:00-08:00"
["event_id"]=> string(6) "314147"
["event_name"]=> string(24) "Practice"
}
Use array_multisort
foreach ($rez->reservation as $value)
{
$dateTime[] = $value->event_start_dt;
}
array_multisort($dateTime,SORT_ASC,SORT_STRING,$rez->reservation);
echo "<pre>";
print_r($rez->reservation);
Check it. this is my code
<?php
$myarray=array(
0 => array
(
'dateTime' => '2013-12-02T10:00:00-08:00',
'chanl1' => '20.10',
'chanl2' => '45.4',
'chanl3' => '',
),
1 => array
(
'dateTime' => '2013-12-02T11:00:00-08:00',
'chanl1' => '20.11',
'chanl2' => '45.4',
'chanl3' => '',
),
2 => array
(
'dateTime' => '2013-12-02T12:00:00-08:00',
'chanl1' => '20.12',
'chanl2' => '33.8',
'chanl3' => '',
),
3 => array
(
'dateTime' => '2013-12-02T09:00:00-08:00',
'chanl1' => '20.9',
'chanl2' => '33.9',
'chanl3' => ''
));
foreach($myarray as $c=>$key) {
$dateTime[] = $key['dateTime'];
}
array_multisort($dateTime,SORT_ASC,SORT_STRING,$myarray);
echo "<pre>";
print_r($myarray);
?>
Output is :
Array
(
[0] => Array
(
[dateTime] => 2013-12-02T09:00:00-08:00
[chanl1] => 20.9
[chanl2] => 33.9
[chanl3] =>
)
[1] => Array
(
[dateTime] => 2013-12-02T10:00:00-08:00
[chanl1] => 20.10
[chanl2] => 45.4
[chanl3] =>
)
[2] => Array
(
[dateTime] => 2013-12-02T11:00:00-08:00
[chanl1] => 20.11
[chanl2] => 45.4
[chanl3] =>
)
[3] => Array
(
[dateTime] => 2013-12-02T12:00:00-08:00
[chanl1] => 20.12
[chanl2] => 33.8
[chanl3] =>
)
)
FIDDLE
Before you can sort the data, you need to create an array which contains as its values the separate items you want to sort. From your debug outputs, these are multiple <reservation> nodes in the input XML, which are children of the element represented by $array/$this->data in those samples (it doesn't matter if it's the root of the document or not, SimpleXML has no Document object).
Your print_r and var_dump output shows that you do not currently have such an array, only a SimpleXML object:
Your first example shows var_dump($array) giving output beginning object(SimpleXMLElement)#275 (1) { - ignore the word array further in, that's just how var_dump is rendering the insides of the object.
Later, you have a print_r($array); beginning array(1) { - but this is only because you've wrapped the real data in a single-element array on the line above ($array = array($this->data);) and that one element ($array[0]) shows as object(SimpleXMLElement)#280 (1) { ....
Note that there's no need to go further and convert all the inner SimpleXML objects into arrays - you just need a list that is sortable, containing the items you are interested in. I would personally use a simple and explicit foreach loop, for maximum code readability, although "cleverer" solutions are available.
Once you have a sortable list, you need a callback function for usort which compares its two parameters. The attempt you've made is along the right lines, but refers to the non-existent (in that function) variable $array; the values you need to compare are the function's arguments, which you've called $a and $b - specifically, you want to compare strtotime($a->event_start_dt) with strtotime($b->event_start_dt).
You can also make the function much simpler, because it follows the common misconception that the return value of the callback should be -1, 0, or 1. In fact, it can be any integer, and only its sign matters - returning -42 will have the same effect as returning -999, namely placing item $a before $b in the resulting array.
I can't easily give a tested example, because you haven't provided the underlying XML to reproduce your input (e.g. echo $this->data->asXML();), but the basic approach I would take would be this:
// Start with an empty array, and add all the items we're interested in to it
$sortable_array = array();
// Loop over all <reservation> children of the SimpleXML object $this->data
// See http://php.net/manual/en/simplexml.examples-basic.php
foreach ( $this->data->reservation as $reservation_node )
{
// Add the individual node to our array
$sortable_array[] = $reservation_node;
}
// Now let's sort out the callback function for the sorting
// This could also be an anonymous function passed directly to usort
function sort_callback_event_start($a, $b)
{
// $a and $b are both items in our $sortable_array, and therefore
// <reservation> nodes which we expect to each have a child
// called <event_start_dt>
// If we convert both dates to Unix timestamps, we have two integers
// to compare, and a simple subtraction gives the desired result
// of <0, 0, or >0 as documented at http://php.net/usort
return
strtotime((string)$a->event_start_dt)
-
strtotime((string)$b->event_start_dt);
}
// Now, we have everything we need to do the actual sorting
usort($sortable_array, 'sort_callback_event_start');
// $sortable_array is now sorted as desired! :D
// Note that the items within it are still SimpleXML objects,
// so you still need to access their properties to do something useful
// e.g. some HTML output with the names listed in order of their start date:
echo '<ol>';
foreach ( $sortable_array as $reservation_node )
{
echo '<li>', (string)$reservation_node->event_name, '</li>';
}
echo '</ol>';
I would just cast it as an array using this function (example function from php.net). But note that this will not sort the XML, rather sort the new array
/**
* function xml2array
*
* This function is part of the PHP manual.
*
* The PHP manual text and comments are covered by the Creative Commons
* Attribution 3.0 License, copyright (c) the PHP Documentation Group
*
* #author k dot antczak at livedata dot pl
* #date 2011-04-22 06:08 UTC
* #link http://www.php.net/manual/en/ref.simplexml.php#103617
* #license http://www.php.net/license/index.php#doc-lic
* #license http://creativecommons.org/licenses/by/3.0/
* #license CC-BY-3.0 <http://spdx.org/licenses/CC-BY-3.0>
*/
function xml2array ( $xmlObject, $out = array () )
{
foreach ( (array) $xmlObject as $index => $node )
$out[$index] = ( is_object ( $node ) ) ? xml2array ( $node ) : $node;
return $out;
}
and pass it the XMLObject
$arrTimes = xml2array(YourSimpleXMLElement);
and then use your original usort function on the new array
function sortByTime($a, $b){
$a = strtotime($a['event_start_dt']);
$b = strtotime($b['event_start_dt']);
if ($a==$b)
return 0;
return ($a < $b) ? -1 : 1;
}
Finally
usort($arrTimes, 'sortByTime');
You have to convert frist in to xml to array using json encode decode
$xml_array = json_decode(json_encode((array)$xml), TRUE);
u will get list of array....than u can sory according to date using strtotime function.
This question already has answers here:
Convert a comma-delimited string into array of integers?
(17 answers)
Closed 9 years ago.
Say I have a string like so $thestring = "1,2,3,8,2".
If I explode(',', $thestring) it, I get an array of strings. How do I explode it to an array of integers instead?
array_map also could be used:
$s = "1,2,3,8,2";
$ints = array_map('intval', explode(',', $s ));
var_dump( $ints );
Output:
array(5) {
[0]=> int(1)
[1]=> int(2)
[2]=> int(3)
[3]=> int(8)
[4]=> int(2)
}
Example codepad.
Use something like this:
$data = explode( ',', $thestring );
array_walk( $data, 'intval' );
http://php.net/manual/en/function.array-walk.php
For the most part you shouldn't really need to (PHP is generally good with handling casting strings and floats/ints), but if it is absolutely necessary, you can array_walk with intval or floatval:
$arr = explode(',','1,2,3');
// use floatval if you think you are going to have decimals
array_walk($arr,'intval');
print_r($arr);
Array
(
[0] => 1
[1] => 2
[2] => 3
)
If you need something a bit more verbose, you can also look into settype:
$arr = explode(",","1,2,3");
function fn(&$a){settype($a,"int");}
array_walk($f,"fn");
print_r($f);
Array
(
[0] => 1
[1] => 2
[2] => 3
)
That could be particularly useful if you're trying to cast dynamically:
class Converter {
public $type = 'int';
public function cast(&$val){ settype($val, $this->type); }
}
$c = new Converter();
$arr = explode(",","1,2,3,0");
array_walk($arr,array($c, 'cast'));
print_r($arr);
Array
(
[0] => 1
[1] => 2
[2] => 3
[3] => 0
)
// now using a bool
$c->type = 'bool';
$arr = explode(",","1,2,3,0");
array_walk($arr,array($c, 'cast'));
var_dump($arr); // using var_dump because the output is clearer.
array(4) {
[0]=>
bool(true)
[1]=>
bool(true)
[2]=>
bool(true)
[3]=>
bool(false)
}
Since $thestring is an string then you will get an array of strings.
Just add (int) in front of the exploded values.
Or use the array_walk function:
$arr = explode(',', $thestring);
array_walk($arr, 'intval');
$thestring = "1,2,3,8,a,b,2";
$newArray = array();
$theArray = explode(",", $thestring);
print_r($theArray);
foreach ($theArray as $theData) {
if (is_numeric($theData)) {
$newArray[] = $theData;
}
}
print_r($newArray);
// Output
Original array
Array ( [0] => 1 [1] => 2 [2] => 3 [3] => 8 [4] => a [5] => b [6] => 2 )
Numeric only array
Array ( [0] => 1 [1] => 2 [2] => 3 [3] => 8 [4] => 2 )
$arr=explode(',', $thestring);
$newstr = '';
foreach($arr as $key=>$val){
$newstr .= $val;
}