PHP reverse the order of sub array - php

Here is an array example I have.
Array
(
[0] => Array
(
[0] => a
[1] => b
[2] => c
)
)
I need the order of the sub array to be reversed. I know the function I need to use is "reverse_array" but I do not know how to apply it to an array within an array.

The function you need to use is array_reverse(), but I'm assuming that's the one you were talking about. To answer your question, you simply specify the array item instead of the main array:
$array[0] = array_reverse($array[0]);
// ^ ^
If you instead wish to reverse all sub-arrays in an array, you can use array_map():
$array = array_map('array_reverse', $array);

Related

PHP - Store an array returned by a function in an already existing array, one by one

Very simplified example:
function returnArray() {
return array('First','Second','Third');
}
$arr = array('hello','world');
$arr[] = returnArray();
print_r($arr);
I was (wrongly) expecting to see $arr containing 5 elements, but it actually contains this (and I understand it makes sense):
Array
(
[0] => hello
[1] => world
[2] => Array
(
[0] => First
[1] => Second
[2] => Third
)
)
Easily enough, I "fixed" it using a temporary array, scanning through its elements, and adding the elements one by one to the $arr array.
But I guess/hope that there must be a way to tell PHP to add the elements automatically one by one, instead of creating a "child" array within the first one, right? Thanks!
You can use array_merge,
$arr = array_merge($arr, returnArray());
will result in
Array
(
[0] => hello
[1] => world
[2] => First
[3] => Second
[4] => Third
)
This will work smoothly here, since your arrays both have numeric keys. If the keys were strings, you’d had to be more careful (resp. decide if that would be the result you want, or not), because
If the input arrays have the same string keys, then the later value for that key will overwrite the previous one. If, however, the arrays contain numeric keys, the later value will not overwrite the original value, but will be appended.
You are appending the resulting array to previously created array. Instead of the use array merge.
function returnArray() {
return array('First','Second','Third');
}
$arr = array('hello','world');
$arr = array_merge($arr, returnArray());
print_r($arr);

How do I reorganize an array in PHP?

I am trying to figure out how to reorganize an array..
I have a multidimensional array(Ill call that original_array) and I would like to take the first array within original_array and set the values as keys in a new array. I also want to take the values of the second array in original_array and make them keys and then set the values of the third array in original_array as the values for those keys.
Here is an example of original_array:
Array (
[id] => Array (
[0] => 1
[1] => 3
)
[reward] => Array (
[0] => Movie
[1] => Trip
)
[cost] => Array (
[0] => 50
[1] => 200
)
)
Basically what I would like to do is look like this:
Array (
[1] => Array (
[Movie] => 50
)
[3] => Array (
[Trip] => 200
)
)
Is there a simple and elegant way to merge these like this?
I have spent hours trying to figure this out using array_merge, array_merge_recursive.. etc. And have search SO far and wide for a similar questions, but I haven't found anything that does what I am after.
I was able to correctly combine the 2nd and 3rd arrays in original_array with array_combine. But, I am at a loss as how to combine that result with the 1st array's values in original_array.
Thanks in advance to any help!
Well, the dirty way would be just use combine array functions like array_combine with the input:
$new_array = array_combine(
$array['id'], // parent keys
// combine chunked combined sub keys :p
array_chunk(array_combine($array['reward'], $array['cost']), 1, true)
);
There may be some incantation of array_*() merging functions that could produce what you're looking for, but it is far easier to just iterate over the original array's [id] sub-array and use its values to create new sub-array keys in a different output array.
// To hold your output
$output = array();
// Iterate the original array's [id] sub-array
foreach ($original['id'] as $idxkey => $newkey) {
// Add a sub-array using $newkey to the output array
$output[$newkey] = array(
// Using the index (not value), retrieve the corresponding reward
// value to use as the new array key
// and corresponding cost to use as the new subarray value
$original['reward'][$idxkey] => $original['cost'][$idxkey]
);
}
Here is a demonstration: https://3v4l.org/2pac3
This should work for you:
First you can get the keys for the main array into a separate variable with array_shift(), which will just remove the first element from your array, which is the array holding the keys.
Then use array_map() to loop through both of your subArrays and use reward as key with the cost values as value and return it in an array. At the end you just have to array_combine() your keys $keys with the new created array.
Code:
<?php
$keys = array_shift($arr);
$result = array_combine($keys, array_map(function($k, $v){
return [$k => $v];
}, $arr["reward"], $arr["cost"]));
print_r($result);
?>
You might wanna take a look at BaseArrayHelper from Yii 2.0 Framework.
Although this file is part of a framework it has only very few dependencies and you should be able to use just this file or parts of it in your code with small modifications.
An example for your use case can be found in the index() method.

php handle arrays

I have an array that contains entries that themselves contain two types of entries.
For simplicity sake, let's say that the entries are like this:
a|1
b|4
a|2
c|5
b|3
etc.
In fact they represent categories and subcategories in my database.
I will use explode to break these entries into letters and digits.
The question is: I want to group them by category.
What's the easiest way to create a multilevel array, which could be sorted by letters:
a|1
a|2
b|4
b|3
c|5
?
How about something like this?
$input = array('a|1','b|4','a|2','c|5','b|3');
$output = array();
foreach($input as $i){
list($key,$val) = explode("|",$i);
$output[$key][] = $val;
}
Output:
Array
(
[a] => Array
(
[0] => 1
[1] => 2
)
[b] => Array
(
[0] => 4
[1] => 3
)
[c] => Array
(
[0] => 5
)
)
<?php
$your_array = array();
$your_array[a] = array('1','2','3');
$your_array[b] = array('4','5','6');
print_r($your_array);
?>
I take it that your entries are strings (relying on the fact that you want to use explode() on them).
If so you can simply sort the array by using sort($array), and then iterate on that array and explode the values and put them in another array, which will be sorted by the previous array's order.

How to reorder array in PHP?

I need to reorder an array in PHP.
The array:
Array
(
[0] => /riado/?p=1
[1] => /riado/?p=2
[2] => /riado/?p=3
[3] => /riado/?p=4
)
How to reorder to:
Array
(
[0] => /riado/?p=4
[1] => /riado/?p=3
[2] => /riado/?p=2
[3] => /riado/?p=1
)
I have searched but I can't find much clues. Can you give me some clues on how to achieve this?
$array = array_reverse($array);
Will reverse the contents of $array, no matter the sort order of the contents.
rsort($array);
Will sort the array in reverse alphabetical order.
rsort($arr);
That should do the trick
A simple rsort should produce the results you require if you want to sort the array in reverse order. (If you simply want to swap the elements from first to last, etc. you could of course use array_reverse or simply iterate over the array from last to first.)
reverse sort example:
<?php
$testArray = array('/riado/?p=1', '/riado/?p=2', '/riado/?p=3', '/riado/?p=4');
rsort($testArray);
print_r($testArray);
?>
array_reverse example:
<?php
$testArray = array('/riado/?p=1', '/riado/?p=2', '/riado/?p=3', '/riado/?p=4');
$testArray = array_reverse($testArray);
print_r($testArray);
?>

How to reset indexes in array_diff result?

I have two arrays: Array ( [0] => 2 [1] => 3 ) and Array ( [0] => 2 ).
I want to get the value, which is not in second array. So I have used the array_diff function but my result will get Array ( [1] => 3 )
Actually this is the result. But a small problem here, its position is (key) 1. I want the result in to a new array starts from 0th position, i.e., Array ( [0] => 3 ).
How can I achieve this?
you can use array_values(array_diff($arr1, $arr2)); if order doesn't matter
You should run array_values() on the result and this would give you a new array with indexes starting at 0.
This is a known shortcoming of array_diff(), check the php docs.

Categories