开发者

Merging multiple multidimensional arrays

开发者 https://www.devze.com 2023-03-19 14:33 出处:网络
I have a variable number of multidimensional arrays but all with the same 4 possible values for each item.

I have a variable number of multidimensional arrays but all with the same 4 possible values for each item.

For example:

Array
    (
            [companyid] => 1      
            [employeeid] => 1
            [role] => "Something"
            [name] => "Something"
    )

but every array may have a different ammou开发者_JS百科nt of items inside it.

I want to turn all the arrays into one single table with lots of rows. I tried array_merge() but I end up with a table with 8, 12, 16... columns instead of more rows.

So... any ideas?

Thanks


Didn't test it, but you could try the following:

$table = array();
$columns = array('companyid' => '', 'employeeid' => '', 'role' => '', 'name' => '');
foreach($array as $item) {
    $table[] = array_merge($columns, $item);
}

This should work since the documentation about array_merge say:

If the input arrays have the same string keys, then the later value for that key will overwrite the previous one.

So you either get the value of the current item or a default value that you can specify in the $columns array.


$array1=Array 
    (
            "companyid" => 1, 
            "employeeid" => 4,
            "role" => "Something",
            "name" => "Something",
    );

$array2=Array 
    (
            "companyid" => array(2,2,2), 
            "employeeid" => 5,
            "role" => "Something2",
            "name" => "Something2"
    );

$array3=Array 
    (
            "companyid" => 3,
            "employeeid" => 6,
            "role" => "Something3",
            "name" => "Something3"
    );
//Using array_merge
$main_array["companyid"]=array_merge((array)$array1["companyid"],(array)$array2["companyid"],(array)$array3["companyid"]);
$main_array["employeeid"]=array_merge((array)$array1["employeeid"],(array)$array2["employeeid"],(array)$array3["employeeid"]);

for($i=0;$i<count($main_array["companyid"]);$i++)
    echo $main_array["companyid"][$i] + "<br />";

for($i=0;$i<count($main_array["employeeid"]);$i++)
    echo $main_array["employeeid"][$i] + "<br />";

I've tested the code above and seems right. You coult also improve this code into a DRY function.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号