aprakasa
aprakasa

Reputation: 47

Combine 2 PHP array into multidimensional

I have 2 separated arrays:

Array
(
    [0] => Header 1
    [1] => Header 2
)

Array
(
    [0] => Array
        (
            [0] => Content #1
            [1] => Content #2
        )

    [1] => Array
        (
            [0] => Content #1.1
        )

)

How to combine those 2 arrays into multidimensional with a format like this below:

Array
(
    [0] => Array
        (
            [Header 1] => Content #1
            [Header 2] => Content #1.1
        )

    [1] => Array
        (
            [Header 1] => Content #2
        )

)

The purpose is to create HTML table. I found a way to create a table from here How to create a HTML Table from a PHP array? but the array format should be like the last one.

Upvotes: 2

Views: 94

Answers (3)

Gyandeep Sharma
Gyandeep Sharma

Reputation: 2327

Here is your solution

Input

$array1 = array('Header 1','Header 2');
$array2 = array(array('Content #1','Content #2'),array('Content #1.1'));

Solution

$new = array();
foreach($array2 as $key => $row){
    for($i=1;$i<=count($row);$i++){
    $new[$key]['Header '.$i] = $row[$i-1];
    }
}

Output

Array
(
    [0] => Array
        (
            [Header 1] => Content #1
            [Header 2] => Content #2
        )

    [1] => Array
        (
            [Header 1] => Content #1.1
        )

)

Upvotes: 0

Nigel Ren
Nigel Ren

Reputation: 57121

A straight forward way using foreach loops...

$arr1 = ['Header 1', 'Header 2'];
$arr2 = [['Content #1', 'Content #2'],
    [ 'Content #1.1']];

$result= [];
foreach ( $arr2 as $arr3 ){
    $partial = [];
    foreach ( $arr3 as $key=>$value )  {
        $partial[$arr1[$key]] = $value;
    }
    $result[] = $partial;
}

print_r($result);

(Pleas excuse the not very inventive variable names)

gives...

Array
(
    [0] => Array
        (
            [Header 1] => Content #1
            [Header 2] => Content #2
        )

    [1] => Array
        (
            [Header 1] => Content #1.1
        )

)

It could be simplified if you knew that the second array always had the same number of values as the first array as you could use array_combine() in the loop instead. Although you could fudge this...

$arr1 = ['Header 1', 'Header 2'];
$arr2 = [['Content #1', 'Content #2'],
    [ 'Content #1.1']];

$result= [];
foreach ( $arr2 as $arr3 ){
    $arr4 = array_slice($arr1,0,count($arr3));
    $result[] = array_combine($arr4, $arr3);
}

print_r($result);

Upvotes: 2

Stanley Aloh
Stanley Aloh

Reputation: 437

I guess you should use the "+" operator i.e $newArray = $array1 +array2

Upvotes: 0

Related Questions