Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I have two array of values and their keys...
First array

    Array
    (
    [0] => Array
        (
            [10] => A1
            [11] => A2
        )

    [1] => Array
        (
            [12] => B1
            [13] => B2
        )

)

Second array

Array
(
  [1] => Z1
  [2] => Z2
)

I want to group these two array into a single array. I mean the array format should be:

Array
(
[0] => Array
    (
        [1] => Z1
        [10] => A1
        [11] => A2
    )

[1] => Array
    (
        [2] => Z2
        [12] => B1
        [13] => B2
    )
 )

I tried with array_push but add the entire array in the [0] position or in the [2] position in the second array.

Anyone has any ideas?

share|improve this question
1  
In what programming language? –  talereader Mar 7 '12 at 9:24
    
PHP. Oops, I forgot to mention that. –  saran Mar 7 '12 at 9:27
add comment

1 Answer

you can try this code

$arrOne = array(
    0 => array(
        10 => 'A1',
        11 => 'A2'
    ),
    1 => array(
        12 => 'B1',
        13 => 'B2'
    )
);

$arrTwo = array(
    1 => 'Z1',
    2 => 'Z2'
);
$arrcountone = count($arrOne);
$arrcounttwo = count($arrTwo);
$i=0;
foreach ($arrOne as $key1 => $value1) {
    $i++;$k=0;
    foreach ($arrTwo as $key => $value) {
        $k++;
        if($i == $k){
            $arrOne[$key1][$key] = $value;
        }
    }
}

var_dump($arrOne) gives

 array
      0 => 
        array
          1 => string 'Z1' (length=2)
          10 => string 'A1' (length=2)
          11 => string 'A2' (length=2)
      1 => 
        array
          2 => string 'Z2' (length=2)
          12 => string 'B1' (length=2)
          13 => string 'B2' (length=2)
share|improve this answer
    
+1 I realized that my answer didn't preserve the array keys. You beat me to it. –  talereader Mar 7 '12 at 10:53
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.