Reputation: 543
I have two array, I want combine it., but for me it not easy.
Edited.
I want convert this array
[poll_answer] => Array
(
[0] => Fasya
[1] => Maulana
)
[poll_image] => Array
(
[0] => 176
[1] => 290
)
to new array like this
[poll_data] => Array
(
[poll_answer] => Fasya
[poll_image] => 176
)
[poll_data] => Array
(
[poll_answer] => Maulana
[poll_image] => 290
)
Upvotes: 2
Views: 40
Reputation: 2984
Now that I understand your question better I believe I came up with a concept answer which should help you head in the right direction with your array:
for ( $i = 0; $i < count ( $array1 ); $i++ )
{
$array['poll_data'] = array(
'poll_answer' => $array1['poll_answer'][$i],
'poll_image' => $array1['poll_image'][$i]
);
print_r($array);
}
In this case I am using the array
keys and taking advantage of the numeric array you have on the second part. An example of what I am doing is $array1['poll_answer'][0]
will output Fasya
. With that in mind, you can reset up the array in a dynamic method and call each part of the array that you need.
Run a for
loop and inside of the loop, inside create a new loop which is what you want. Your output should be:
Array
(
[poll_data] => Array
(
[poll_answer] => Fasya
[poll_image] => 176
)
)
Array
(
[poll_data] => Array
(
[poll_answer] => Maulana
[poll_image] => 290
)
)
I noticed you want the same keys, for that you actually have to use array_merge_recursive
which will preserve your array keys in the same way. PHP Manual says:
array_merge_recursive() merges the elements of one or more arrays together so that the values of one are appended to the end of the previous one. It returns the resulting array.
So the same setup, and instead of joining the arrays with array_merge
use array_merge_recursive
:
$c_array = array_merge_recursive($array1, $array2);
For more information on array_merge_recursive
you can check our their documentation on PHP Manual, there will be also some examples you can check out.
Cheers
You can simply use array_merge
, as per PHP Manual documentation:
Merges the elements of one or more arrays together so that the values of one are appended to the end of the previous one. It returns the resulting array.
This is what the syntax looks like:
array array_merge ( array $array1 [, array $... ] )
$array1
is the main arrayarray $...
is the other arrays that you want to merge with the initial array.Now in practice, this is what it would look like:
<?php
$array1 = array(
'poll_data' => array(
'poll_answer' => 'Fasya',
'poll_image' => 176
)
);
$array2 = array(
'poll_data' => array(
'poll_answer' => 'Maulana',
'poll_image' => 290
)
);
Then call the array_merge
function
$c_array = array_merge($array1, $array2);
For more details on what the overall aspect of array_merge
is you can always check out their documentation on PHP Manual. It will explain each parameter, and it will also have some examples for your to look at.
Upvotes: 1