First is a solution that will consume the input arrays in a loop while building the new structure. You can always cache separate copies of the input if you need them elsewhere. Show Nội dung chính
All solutions below will work even if the two arrays have different lengths -- any remaining elements will be appended to the end of the result array after the loop. Code: (Demo)
Another way without consuming the input arrays is to build lookup arrays: Code: (Demo)
Or you could use Code: (Demo)
This is not working as it replaces the value of data. How can I have it add an associative value each loop though? Nội dung chính
MaxiGui 5,8864 gold badges14 silver badges32 bronze badges asked Mar 21, 2011 at 23:11 You can simply do this
If your're running on php 5.4+
answered Sep 8, 2014 at 5:52 4 I think you want Or in case you want an array that maps categories to array of questions:
webvitaly 4,1217 gold badges29 silver badges46 bronze badges answered Mar 21, 2011 at 23:13 ThiefMasterThiefMaster 302k78 gold badges581 silver badges625 bronze badges 2 Before for loop:
Then in your loop:
Uwe Keim 38.6k56 gold badges173 silver badges281 bronze badges answered Mar 21, 2011 at 23:12 moemoe 28.1k3 gold badges18 silver badges16 bronze badges 6 I know this is an old question but you can use:
This will push the
lasec0203 2,2141 gold badge19 silver badges35 bronze badges answered Jun 29, 2017 at 15:54 MikeMike 1,7282 gold badges42 silver badges73 bronze badges For anyone that also need to add into 2d associative array, you can also use answer given above, and use the code like this
you can then call it (to test out the result by:
which should print $question answered Dec 19, 2017 at 7:34 maximranmaximran 4054 silver badges11 bronze badges How do I add associative array to array in PHP?Use the array_merge() Function to Add Elements at the Beginning of an Associative Array in PHP. To add elements at the beginning of an associative, we can use the array union of the array_merge() function. How do you add to an associative array?Normally add a new element in an existing associative array it will get appended at the end of that array.. Example: <? ... . Syntax: array array_merge( $arr1, $arr2 ) ... . Syntax: $arr3 = $arr1 + $arr2.. Program: PHP program to add a new item at the beginning of an associative array.. How do you sum an associative array in PHP?The array_sum() function returns the sum of all the values in an array(one dimensional and associative). It takes an array parameter and returns the sum of all the values in it. How do I get associative array in PHP?Answer: Use the PHP array_values() function You can use the PHP array_values() function to get all the values of an associative array. |