Why does the array_push() "deepen" the depth of an array? - php

I have a two dimensional array, lets call it BASE.
Now I wanto to iterate over this array with a foreach loop, and each time push the currently selected array into a new array.
foreach($BASE as $array){
$newarray = [];
array_push($newarray, $array);
$newarraylength = count($newarray[0])
//some more code
}
This way, I want to accomplish being able to iterate over the pushed array inside a for-loop nested inside this foreach loop, like this
for(index = 0; index < $newarraylength; $index++){
newarray[0][index]
}
However, when the array from the BASE array is pushed into the new array, this new array for some reason becomes threedimensional Oo
Therefore, the syntax above doesn't work.
So, either someone of you please tell me how to deal with looping through this threedimensional array. Because my head doesn't manage to find a solution to this.
Or someone please tell me how to push a 1-dimensional array into another 1-dimensional, still empty array, without creating a 3-dimensional array.

I believe what you want to do is:
foreach($BASE as $array){
$newarray = [];
array_push($newarray, $array);
$newarraylength = count($newarray[0])
//some more code
}
What you've done is to push the whole two dimensional array.
So if $BASE is:
array(
'1' => array('a', 'b'),
'2' => array('c', 'd')
)
Then pushing that to $newarray would result in
$newarray =
array(
0 => array(
'1' => array('a', 'b'),
'2' => array('c', 'd')
)
);

what you are basically trying to achieve is:
foreach($BASE as $array){
$newarray = [];
array_push($newarray, $array);
$newarraylength = count($newarray[0])
//some more code
for(index = 0; index < $newarraylength; $index++){
//your code with newarray[0][index] here
}
}
but could use two nested foreach
foreach($BASE as $array){
foreach($array as $key=>$value){
}
}
keep in mind that the first method will only work with non associative array...

Related

How to merge a multidimensional array into one single dimension array

I have a multi dimension array that I want to merge all the inside arrays into one singer dimension array, I have tried array_merge with foreach but it doesn't help.
Example Array:
$nums = array (
array(1,2,3),
array(4,5,6),
array(7,8,9)
);
What I did but get an empty array
$newArr = [];
foreach ($nums as $value) {
array_merge($newArr, $value);
}
Expectation
$newArr = array(1,2,3,4,5,6,7,8,9)
You could use the function array_merge() this way :
$newArr = array_merge(...$nums)
It would make your code lighter and avoid the use of a foreach loop.
array_merge returns the results of the merge rather than acting on the passed argument like sort() does. You need to be doing:
$newArr = array_merge($newArr, $value);

duplicating a value inside array with using a value in another array PHP

hi i have three array like this
$arr1 = array(2,3,4,5);
$arr2 = array(1,2,3,4);
$arr3 = array();
i need a loop function to duplicate each of the value inside $arr2 with the value inside $arr1 so the end result should look like this:
$arr3= array(1,1,2,2,2,3,3,3,3,4,4,4,4,4,4);
i know that i need to do an array_push into the $arr3 with $arr2[i] by doing this
for($i=0;$i < count($arr2);$++){
array_push($arr3,$arr2[$i]);
}
but i dont know the outer loop for iterating the array_push loop, what should i add to do the duplicating?
Solution 1: You need to apply a foreach() and for() loop
1.Iterate over the first array $arr1
2.Check that value with the same key of the first array exists or not in the second array
3.Apply a loop based on first array values
4.Assign same value repeatedly based on loop
foreach($arr1 as $key=>$arr){
if(isset($arr2[$key])){
for($i=0;$i<$arr;$i++){
$arr3[] = $arr2[$key];
}
}
}
print_r($arr3);
Output:-https://eval.in/1005648
Solution 2: You can use array_merge() and array_fill()
foreach($arr1 as $key=>$arr){
$arr3= array_merge($arr3,array_fill(count($arr3),$arr,$arr2[$key]));
}
echo "<pre/>";print_r($arr3);
Output:-https://eval.in/1005666

Individually sorting subarrays of an array in PHP

I have an array of numeric subarrays. I want to sort all the subarrays, and then sort the whole array, and remove duplicates. Using sort($val) doesn't work, so I found the following workaround with $derp, which I find insanely stupid:
$arr = array( array(5,6), array(1,2), array(6,5) );
foreach ($arr as $key => $val) {
$derp = $val;
sort($derp);
$arr[$key] = $derp;
}
sort($arr);
$arr = array_map("unserialize", array_unique(array_map("serialize", $arr)));
The result is array( array(1,2), array(5,6) ). Is that is the correct way to do this in PHP, or is there a better and shorter way?
I created a pastebin as a response to the first answer: pastebin.com/Y5vNvKKL
This question is not anymore just about a less goofy way to write this: Now the question is:Why does sort() in array_work() not give the same result as sort() in foreach?
By the way: This is about finding the partitions of multisets.
I'd approach it like this:
array_walk($arr, 'sort');
$deduped = array();
foreach ($arr as $val) {
$deduped[serialize($val)] = $val;
}
$arr = array_values($deduped);

Shuffle an array of Q&A pairs

What is the best way you think to shuffle a multi-dimensional array in the following structure, so that question-answer pairs are separated?
$myArray = array(
array('question' => 'q1', 'answer' => 'a1'),
array('question' => 'q2', 'answer' => 'a2'),
array('question' => 'q3', 'answer' => 'a3')
//...
//...
);
What I need is to turn this:
q1-a1, q2-a2, q3-a3...
into this:
q3-a2, q4-a3, q1-a9...
I get this array from a questions database. I want to display question-answer pairs but shuffled obviously. I have a few solutions in my mind, just curious for clever ways to do it ;)
Well you could just simply get the questions and answers, shuffle them, then reapply:
$q = $a = array();
foreach ($myArray as $value) {
$q[] = $value['question'];
$a[] = $value['answer'];
}
shuffle($q);
shuffle($a);
foreach($myArray as $key => &$value) {
$value['question'] = $q[$key];
$value['answer'] = $a[$key];
}
echo '<pre>';
print_r($myArray);
You could also use array_collumn() if available (PHP 5 >= 5.5.0):
$q = array_column($myArray, 'question');
$a = array_column($myArray, 'answer');
PHP has a plethora amount of built-in array functions. Using a combination of these functions, you could create a custom shuffle function that uses array_keys, array_values, shuffle and array_combine internally. Try the following:
// Create a copy of the original array to key
// for processing later...
$originalArray = $myArray;
function shuffleAll($myArray) {
// Pull the keys into an array and
// pull the values into another
// array...
$keys = array_keys($myArray);
$values = array_values($myArray);
// Shuffle the arrays independently...
shuffle($keys);
shuffle($values);
// Combine the arrays into one...
return array_combine($keys, $values);
}
$myArray = shuffleAll($myArray);
$myArray should now have a custom assortment of your now non-matching key-value pairs. The original values have been preserved in $originalArray for latter processing and matching.
References:
array_combine(...)
array_keys(...)
array_values(...)
shuffle(...)

maximum value in php array for each key value

I want to find out the maximum value of the each key in the array
$arr1= array(
0=>array(1,2,3),
1=>array(2,4,6),
2=>array(25,4,5));
}
I want to find the maximum value for each value for the corresponding key
The final output shuld be
$max_array = array(25,4,6);
with the below code i get error max(): When only one parameter is given, it must be an array in
foreach ($res_arr as $k=>$subArray) {
foreach ($subArray as $id=>$value) {
$spanmaxArray[$id] = max($value);
}
}
First, rotate array to makes columns as lines
$arr1= array(
0=>array(1,2,3),
1=>array(2,4,6),
2=>array(25,4,5)
);
$arr2 = array();
foreach($arr1 as $subArray) {
foreach($subArray as $k=>$v) {
$arr2[$k][] = $v;
}
}
Then, use array_map as #HamZa did
$max_array = array_map('max', $arr2);
print_r($max_array);
foreach ($res_arr as $k=>$subArray){
$max = 0;
foreach ($subArray as $id=>$value){
if ($value>$max){
$max = $value;
}
}
$spanmaxArray[$k] = $max;
}
Try this.
Definitely the shortest version:
$max_array = array_map('max', $arr1);
array_map() takes each element array of $arr1 and applies max() to it.
Edited after seeing that max in each column position is desired:
$sorted = array();
for ($i = 0; $i <=2; $i++) {
$sorted[$i] = array_column($input, $i);
}
This loops over the array and applies array_column() to each (requires PHP 5.5).
So:
$sorted = array();
for ($i = 0; $i <=2; $i++) {
$sorted[$i] = array_column($arr1, $i);
}
$max_array = array_map('max', $sorted);
working version
You only need one loop, because the max function takes an array as a parameter. But the answer you are giving is wrong, unless I've misunderstood the problem.
I think what you're after is:
$max_array = array_map('max', $arr1);
All of the earlier answers are working too hard.
Use array_map() as the iterating function.
Unpack your multidimensional array with the "spread/splat operator" (...); in other words, convert your single array containing three subarrays into three separate arrays.
Call max() on the three elements as they are synchronously iterated by array_map().
Code: (Demo)
$arr1 = [
[1, 2, 3],
[2, 4, 6],
[25, 4, 5],
];
var_export(array_map('max', ...$arr1));
The above is a more versatile and concise version of the following one-liner which has the same effect on the sample array:
var_export(array_map('max', $arr1[0], $arr1[1], $arr1[2]));
Output:
array (
0 => 25,
1 => 4,
2 => 6,
)
*A note for researchers: if processing a multidimensional array that has associative first level keys, you will need to index the first level so that the splat operator doesn't choke on the keys.
...array_values($array)

Categories