0

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

3
  • 1
    $my_arrays[] = array("foo" => "bar"); Commented Jul 1, 2021 at 4:20
  • Not really sure what you mean here - can't see how this will allow a loop or generate the structure I am after... Commented Jul 1, 2021 at 4:31
  • My apologies Salman - that is actually exactly correct! Commented Jul 1, 2021 at 5:00

2 Answers 2

2

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
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks very much, the [] was the bit I was missing - I never even knew about it! I have modified my code in the PHP Sandbox to include code that works for my sample with the loop.
1

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
        )

)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.