I have this array of arrays
array (size=2)
'login' =>
array (size=3)
20 =>
array (size=1)
0 =>
object(File)[3]
10 =>
array (size=1)
0 =>
object(Database)[4]
5 =>
array (size=1)
0 =>
object(Closure)[5]
I'm trying to reorder the position of the keys in the second level arrays (where it says 20, 10, 5) so the result should be
array (size=2)
'login' =>
array (size=3)
5 =>
array (size=1)
0 =>
object(File)[3]
10 =>
array (size=1)
0 =>
object(Database)[4]
20 =>
array (size=1)
0 =>
object(Closure)[5]
The problem is that I can't figure out how to do that so please help
You need to do
ksort($array['login']);
This will sort the array keys so they are ascending. If you wanted them descending you would do
krsort($array['login']);
PHP has lots of handy functions for sorting arrays
You could have a look at Array Sorting and find out, that 'ksort' is your choice ;-)
Try PHPs ksort function on your second level array: http://php.net/ksort
It will sort your array by key while maintaining the key-data-associations
PHP has a variety of array sorting functions.
In your case, the most appropriate would seem to be ksort(), which is summarised thus:
Sorts an array by key, maintaining key to data correlations.
As pointed out in the comments, your particular example is already in the reverse of the required order; if this can be guaranteed, you could also use array_reverse(), being sure to pass the optional $preserve_keys parameter as true.
Specifically, you want to re-order the sub-array with the key 'login'; assuming your overall array is called $data, you would want to write this:
ksort($data['login']);
// note no need for an assignment, as PHP's sort functions act in-place
or this:
$data['login'] = array_reverse($data['login'], true);
// assign back to the original variable, as array_reverse() returns a new array
Related
I need an array sorted by Unix timestamp values. I attempted to use both ksort and krsort before realising that occasionally the timestamp values might be the same (and you cannot have duplicate keys in arrays).
Here's an example array I may be faced with:
$array = array(
[
"unix" => 1556547761, // notice the two duplicate unix values
"random" => 4
],
[
"unix" => 1556547761,
"random" => 2
],
[
"unix" => 1556547769,
"random" => 5
],
[
"unix" => 1556547765, // this should be in the 3rd position
"random" => 9
]
);
So what I'm trying to do is sort them all based on each child arrays unix value, however I cannot figure out how to do so. I have tried countless insane ways (including all other sort functions and many, many for loops) to figure it out - but to no avail.
All help is appreciated.
You can use usort which sort your array by given function
Define function as:
function cmpByUnix($a, $b) {
return $a["unix"] - $b["unix"];
}
And use with: usort($array, "cmpByUnix");
Live example: 3v4l
Notice you can also use asort($array); but this will compare also the "random" field and keep the key - if this what you need then look at Mangesh answer
array_multisort() — Sort multiple or multi-dimensional arrays
array_columns() — Return the values from a single column in the input array
You can use array_multisort() and array_column(), then provide your desired sort order (SORT_ASC or SORT_DESC).
array_multisort(array_column($array, "unix"), SORT_ASC, $array);
Explanation:
In array_multisort(), arrays are sorted by the first array given. You can see we are using array_column($array, "unix"), which means that the second parameter is the order of sorting (ascending or descending) and the third parameter is the original array.
This is the result of array_column($array, "unix"):
Array(
[0] => 1556547761
[1] => 1556547761
[2] => 1556547765
[3] => 1556547769
)
This function sorts an array such that array indices maintain their correlation with the array elements they are associated with. This is used mainly when sorting associative arrays where the actual element order is significant.
Note:If two members compare as equal, their relative order in the sorted array is undefined.
Refer : https://www.php.net/manual/en/function.asort.php
asort($array);
echo "<pre>";
print_r($array);
echo "</pre>";
It will give you the output as
Array
(
[1] => Array
(
[unix] => 1556547761
[random] => 2
)
[0] => Array
(
[unix] => 1556547761
[random] => 4
)
[3] => Array
(
[unix] => 1556547765
[random] => 9
)
[2] => Array
(
[unix] => 1556547769
[random] => 5
)
)
You can keep the array key [1],[0],[3],[2]) as it is Or you can keep it as sequential as per your requirement.
I have a section of an array defined:
$arrData['categories'] = array();
array_push($arrData['categories'],array("category" => array(array("label"=>"Beef"),array("label"=>"Chicken"))));
array_push($arrDAta['categories'][0]['category'],array("label"=>"pork"));
The arrays are nested so that it encodes into JSON properly with all the {[{[{[]}]}]} formatted properly.
However, I need to create these types of meats dynamically, not statically. When I try to add onto the array in the third line of code to simulate dynamic creation, it throws an error:
Warning: array_push() expects parameter 1 to be an array, null given
Well, $arrData['categories'][0]['category] IS an array, so why does it shoot me down?
To show myself that I'm not crazy, I var_dump $arrData['categories'][0]['category'] and get an array of size 1:
array (size=1)
'category' =>
array (size=2)
0 =>
array (size=1)
'label' => string 'Beef' (length=4)
1 =>
array (size=1)
'label' => string 'Chicken' (length=7)
Its the capitalization. In the third line the variable $arrDAta is capitalized differently than the others ($arrData)
I am new to php. Please let me know how do I count number of array entry in under array 80cb936e55e5225cd2af.
array
'status' => int 1
'msg' => string '2 out of 1 Transactions Fetched Successfully' (length=44)
'transaction_details' =>
array
'80cb936e55e5225cd2af' =>
array
0 =>
array
...
1 =>
array
...
Assuming your array variable is $arr : ...
$count = count($arr['transaction_details']['80cb936e55e5225cd2af']);
(But this will only count the indexes/integers of that sub-array, not the values inside them!)
You can use PHP's count() like this
$noOfEntries = count($array['transaction_details']['80cb936e55e5225cd2af']);
This will get you the number of arrays inside 80cb936e55e5225cd2af (not the overall amount of elements).
I've Googled it for two days, and tried looking at the PHP manual, and I still can't remember that function that aligns the key values for PHP arrays.
All I'm looking for is the function that takes this:
Array
(
[0] => 1
[3] => 2
[4] => 3
[7] => 4
[9] => 5
)
And converts it into this:
Array
(
[0] => 1
[1] => 2
[2] => 3
[3] => 4
[4] => 5
)
Basically, the array is first sorted by key (their values attached to them stay with them), then all the keys are set to all the counting numbers, consecutively, without skipping any number (0,1,2,3,4,5,6,7,8,9...). I saw it being used with ksort() a few months ago, and can't see to remember or find this elusive function.
Well, you see, this one is hard, because the general description on the PHP array functions page does not say that this function does what you're looking for.
But you can sort the array using ksort(), and then use this: array_values() . From the page from the PHP manual:
array_values() returns all the values from the input array and indexes numerically the array.
You can use array_merge:
$array = array_merge($array);
It will reindex values with numeric keys.
Update: Using array_values as proposed in #LostInTheCode's answer is probably more descriptive.
function array_reset_index_keys($array)
{
$return = array();foreach($array as $k => $v){$return[] = $v;}return $return;
}
And then use like a regular function, should re index the array
you can also use native functions such as array_values which returns the values of an array into a single dimension array, causing it to be re indexed .
Good day everyone.
I have an regular array (this is the print_r result, the array can have from 1 to n positions):
Array
(
[1] => value1
[2] => value2
[3] => value3
)
I have another array defined elsewhere as:
$array_def['value1']['value2']['value3'] = array(
'fl' => 'field1',
'f2' => 'field2',
);
Using the first array result, how can i check if $array_def exists? In other words, i need to use a flat array values to check if a multidimensional array correspondence exists; keep in mind that the values can repeat in the first array, therefore flipping values with keys it's not an option as it will collide and remove duplicated values.
Thanks in advance.
You can do it this way:
$a = array(1=>'value1', 2=>'value2', 3=>'value3');
$array_def[$a[1]][$a[2]][$a[3]] = array(
'fl' => 'field1',
'f2' => 'field2',
);
I don't think there's any shortcut or special built-in function to do this.
Found the perfect function for you. returns not only exists, but position within a multi-dimensional array..
http://www.php.net/manual/en/function.array-search.php#47116
dated: 03-Nov-2004 11:13
too much to copy/paste
you can then loop over your flat array and foreach:
multi_array_search($search_value, $the_array)