Alex
Alex

Reputation: 7688

dynamically create arrays from multidimensional array

So if having a multidimensional array like:

Got it from here (as a demo): PHP. Loop through an array and get items with attributes in common

$data

Array
(
    [0] => stdClass Object
        (
            [term_id] => 3
            [name] => Comercial
        )

    [1] => stdClass Object
        (
            [term_id] => 4
            [name] => Escolar
        )

    [2] => stdClass Object
        (
            [term_id] => 5
            [name] => Kinder
        )

    [3] => stdClass Object
        (
            [term_id] => 6
            [name] => Primaria
        )

    [4] => stdClass Object
        (
            [term_id] => 7
            [name] => Secundaria
        )

    [5] => stdClass Object
        (
            [term_id] => 1
            [name] => Uncategorized
        )

)

Having 0,1,2,3,4,5 stdClass Objects, how can I create individual arrays for each std Object dynamically.

By that I mean that the function should be able to create $varX array, where X is the array number of the stdObject, automatically...

$var0 = $data[0]; $var1 = $data[1]; and so on, determined by $data first level count of arrays.


Edit: I got carried away and forgot to mention the most important question:

Having $var0, $var1... is very important because for a later use of all or each one individually.

So

Ok, that function works partially because from there I don't know how to make it automatically add $val1,$val2... to (ex:) array_intersect($val1,$val2,$val3...

Upvotes: 1

Views: 1304

Answers (3)

Francois Deschenes
Francois Deschenes

Reputation: 24969

The easiest way would be to use extract.

extract($data, EXTR_PREFIX_ALL, 'var');

With that said, it will add an underscore (_) after the prefix (e.g. var_0).

Update:

Regarding your edit, you could simply call array_intersect using call_user_func_array. There's no need for variables.

call_user_func_array('array_intersect', $data);

Upvotes: 2

Joe
Joe

Reputation: 15802

You can just cast each object to an array.

foreach ($data AS $key => $datum)
{
    $data[$key] = (array) $datum;
}

For your update:

foreach ($data AS $key => $datum)
{
    $newkey = 'var' . $key; // we want the variable to be called "var" plus the number
    $$newkey = (array) $datum; // Make it an array
    $data[$key] = $$newkey; // And update the $data array to contain the array
}

You now have $var0, $var1, etc and can also access them as a collection in $data, and they're in both as an array.

Upvotes: 0

James Lin
James Lin

Reputation: 26528

foreach ($data as $key => $obj)
{
  $key = 'var'.$key;
  $$key = $obj;
}

Upvotes: 0

Related Questions