Append each item of arrays to a new array [duplicate] - php

This question already has an answer here:
Multi dimensional loops from 4 existing arrays [duplicate]
(1 answer)
Closed 4 months ago.
I have 4 different arrays with the same count of elements. I want to add each element of each array into a new array. For example: $id_array[0] should be added into $artikel_combined. Then $name_array[0] into $artikel_combined. And so on. Then when all 4 arrays are done with index 0, then they should start with index 1 and so on.
I tried with this code but it just combines all the arrays, but not what i want.
// LoadIni creates an array every nth line.
$id_array = $ini_obj->LoadIni($f_art, 0, 9, 999);
$name_array = $ini_obj->LoadIni($f_art, 1, 9, 999);
$x_array = $ini_obj->LoadIni($f_art, 2, 9, 999);
$y_array = $ini_obj->LoadIni($f_art, 4, 9, 999);
// This is the point where i fail, because it just combines and I'm out of ideas
$arr = array_merge($id_array, $name_array, $x_array, $y_array);
$artikel_combined = [];
// Removing new Lines from the elements
foreach ($arr as $item) {
$artikel_combined[] = trim($item);
}

if the array have always the same count of elements you can cycle through them and add them together.
like
$count = count($id_array);
$artikel_combined = [];
for($i=0;$i<$count;$i++){
$artikel_combined[$i][] = id_array[$i];
$artikel_combined[$i][] = trim(name_array[$i]);
$artikel_combined[$i][] = trim(x_array[$i]);
$artikel_combined[$i][] = trim(y_array[$i]);
}
probably not the best way to solve the problem, but it should do the job :)

Using array_merge: "Merges the elements of one or more arrays together so that the values of one are appended to the end of the previous one."
But you want to join up the same array key for every array into a new array, resulting in a multidimensional array.
You could also do so using array_map passing null as the first parameter:
// LoadIni creates an array every nth line.
$id_array = $ini_obj->LoadIni($f_art, 0, 9, 999);
$name_array = $ini_obj->LoadIni($f_art, 1, 9, 999);
$x_array = $ini_obj->LoadIni($f_art, 2, 9, 999);
$y_array = $ini_obj->LoadIni($f_art, 4, 9, 999);
$artikel_combined = array_map(null, $id_array, $name_array, $x_array, $y_array);

Related

How to save array variables in antoher array PHP

I am making question like 3 * 5 = ? and ? * 5 = 15. To make this, I will save an array variable ($arrayTotalQuestions) with the number 1 to 10 and an array variable ($arrayAnswers)
with the number 5,10,15,20,25,30,35,40,45,50 inside $array1. I will loop these 2 rows 20 times in my table like this:
foreach($array1 as $array1) {
echo $array1[array_rand($array1)];
}
The (array)variables inside the array:
$arrayTotalQuestions = range(1, 10);
$number = 5;
$arrayAnswers = (5, 10, 15, 20, 25, 30, 35, 40, 45, 50);
Now I want to store these 3 variables inside another array named $array1:
$array1 = array(
"<tr><td>$this->arrayTotalQuestions</td> <td>x</td> <td>$this->number</td> <td>=</td> <td><input type='text' name='txtAnswer[$this->arrayTotalQuestions]'></td></tr>",
"<tr><td><input type='text' name='txtAnswer[$this->arrayAnswers]' value=''></td> <td>x</td> <td>$this->number</td> <td>=</td> <td>$this->arrayAnswers</td></tr>"
);
But I am getting the error "array to string conversion...", because of the array variables inside $array1.
How can I solve this?
Like the error says you're trying to convert an array to a string, which isn't possible.
Take a look at this example:
<?php
$array = [1,2,3,4,5];
$newVar = "This is my array: $array";
?>
This results in the error E_NOTICE : type 8 -- Array to string conversion -- at line 3.
You're trying to output an array, which has multiple values in it, as part of your string. PHP doesn't know how you want to do this (should it just list all the array vars? Does it put a space between them? A comma? A comma and a space? etc)
So, instead, you need to convert the array into a string yourself. One way you can do this is to use the join() function in PHP.
join() takes 2 parameters: separator and array and outputs a string which is all the array values separated by your separator.
So the above example becomes:
<?php
$array = [1,2,3,4,5];
$newVar = "This is my array: ".join(", ", $array);
?>
Which outputs This is my array: 1, 2, 3, 4, 5
Updated based on comment
To use 2 or more arrays in the same foreach loop you just need to change it into a for loop:
for($i = 0, $i < count($array1); $i++) {
echo $array1[$i].': '.$array2[$i];
}
There is a way to do it with a foreach loop too, but I find that this isn't quite as clean a way to do this for maintenance (just my preference).
foreach($array1 as $index => $value) {
echo $value.': '.$array2[$index];
}

Shifting the items in an array by a specified value

How would you go about circularly rotating the items in an array up or down by a specified value. For example
$value = 1; // circularly rotate by 1
$array = array(1,2,3,4,5);
// Should return
array(2,3,4,5,1);
The entire array is circularly rotated anti-clockwise by 1. 1 went to the end and 2 became the leading number in the array. I cannot find a reliable way to do this.
Use a for-loop with a specification on how many items you want moved, and array_shift() to shift the array. Then add the first element to a shifted array (which essentially moves the first item to the last element)
$shift = 2; // How many times you want to move it
$output = array(1, 2, 3, 4, 5);
for ($i = 0; $i < $shift; $i++) {
array_push($output , array_shift($output));
}
print_r($output); // 3, 4, 5, 1, 2
Live demo
References
http://php.net/manual/en/function.array-shift.php
http://php.net/manual/en/function.array-push.php
You can combine the array_push function that adds a value to the end of an array and the array_shift function that removes and returns the first element of an array.
<?php
$value = 1; // circularly rotate by 1
$array = array(1,2,3,4,5);
while ($value) {
array_push($array, array_shift($array));
$value--;
}
print_r($array);
?>

Merge two arrays alternatively [duplicate]

This question already has answers here:
Merge two flat indexed arrays of equal size so that values are pushed into the result in an alternating fashion
(2 answers)
Closed 6 years ago.
What I want is an efficient (without looping) way to merge arrays in the way that the first element of the resulting array is the first element of the first array, the second element of the resulting array is the second element of the second array (alternatively)... etc
Example:
$arr1 = array(1, 3, 5);
$arr2 = array(2, 4, 6);
$resultingArray = array(1, 2, 3, 4, 5, 6);
assuming both arrays have the same length.
$arr1 = array(1, 3, 5);
$arr2 = array(2, 4, 6);
$new = array();
for ($i=0; $i<count($arr1); $i++) {
$new[] = $arr1[$i];
$new[] = $arr2[$i];
}
var_dump($new);
Not that I'd really advocate this "hack", but this'll do:
$result = array();
array_map(function ($a, $b) use (&$result) { array_push($result, $a, $b); }, $arr1, $arr2);
It really just hides a double loop behind array_map, so, meh...

PHP array_push index retention

I am looping through an array which itself contains array to find indexes of values 5 & 6.
Upon finding these indexes, I push the matched array, using array_push, into a another array. My application depends on maintaining the array indexes but array_push resets the keys to 0, 1, 2 etc rather than the matched 5, 6, 7 etc.
Rather than calling array_push you can add element this way:
$arr[5] = array("foo", "bar");
$arr[6] = array("red", "blue");
$arr[7] = array("123", "567");
Would that do or did I miss something?
$newArray = array();
foreach( $myArrays as $myArray )
if( ($result = array_search(5, $myArray)) || ($result = array_search(6, $myArray))
$newArray[$result] = $myArray[$result];

Randomly picking out of an array in PHP

I have an array that has values like 1, 5, 6, 9, 11, 45, 56, etc. What I'm trying to do is to randomly one value, perhaps 6. Then I want to pick a random value excluding 6 (so no doubles). Then a random value excluding the last two, all from inside an array. Any help? I'm trying to do this without while loops but if they are necessary then so be it.
I suggest the following:
# pick a random key in your array
$rand_key = array_rand($your_array);
# extract the corresponding value
$rand_value = $your_array[$rand_key];
# remove the key-value pair from the array
unset($your_array[$rand_key]);
See: array_rand, unset.
Shuffle the array first and then use it as a stack:
$a = array(1, 5, 6, 9, 11, 45, 56);
shuffle($a);
// now you can have your picks:
$pick = array_pop($a);
$pick = array_pop($a);
$pick = array_pop($a);
$pick = array_pop($a);
...
I would probably shuffle the array and get the first/last x value

Categories