1

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 ammount 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

2
  • Try adding them together with +. $array = $array + another_array; Commented Jul 12, 2011 at 19:54
  • Please can you add some more example arrays. I am not sure what you mean by "different amounts of items inside it". Do you mean sometimes the values are blank? or that you can have multiple groups of 4 values inside a single array? Commented Jul 12, 2011 at 20:17

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

Comments

1
$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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.