Reputation: 29
This is code that produces the array of associated arrays that I need to input into a PHPWord cloneBlock() routine.
// Start with 2 associative arrays, both having the same key
$array1 = array('course' => 'Text1');
$array2 = array('course' => 'Text2');
// create an array of arrays
$my_arrays = array($array1, $array2);
The array of associated arrays result looks like this:
array(2) {
[0]=>
array(1) {
["course"]=>
string(5) "Text1"
}
[1]=>
array(1) {
["course"]=>
string(5) "Text2"
}
}
Now I want to produce the same result but in a loop as I do not know how many associated arrays will be in my main array.
I have tried array_merge() but that gets rid of elements that have duplicate keys.
Also tried array_merge_recursive() but that takes the keys out of the inner arrays and puts it outside & puts numeric keys into the inner arrays.
Is there another way to create the result I am after?
I have put my failed attempts here: https://extendsclass.com/php-bin/4e2b3b2
Upvotes: 0
Views: 65
Reputation: 934
Best I can tell this gives the desired output:
$result = array();
for($i = 0; $i < 3; $i++){
array_push($result, array('course' => "Text$i"));
}
$result = array_merge($result, array());
Should output:
Array
(
[0] => Array
(
[course] => Text0
)
[1] => Array
(
[course] => Text1
)
[2] => Array
(
[course] => Text2
)
)
Upvotes: 1
Reputation: 129
Try like this:
//init your array
$my_arrays = [];
//push first array
$my_arrays[] = $array1;
//push second array
$my_arrays[] = $array2;
//push xxx array
//push first array
$my_arrays[] = $xxx;
//and go on
Upvotes: 2