Jump to content

Set associative array at pointer


Drongo_III

Recommended Posts

Hi Guys

 

I don't know whether this is possible or not but I've been going down a lot of dead ends for a few hours now and I'm ready to defer to a higher power...

 

I want to create a function that will accept an array of keys as it's first argument and a value as it's second argument and basically add the keys in a multidimensional format to produce an array with the data as its final value.

 

So if I passed into the function:

someFunc(array('key1','key2'), 'data');

I would end up with an array that looks like: [key1][key2] = 'data'

 

I've been trying to do it with a while loop but I become unstuck in adding the subsequent layers to the array. I've also explored using the 'end' and 'key'  method hoping I could just specify the pointer and add an element there but there doesnt appear to be anything like that.  Any help is very welcome!

 

Dronogo

 

 

 

 

 

 

Link to comment
Share on other sites

I'd add an empty result array to that function's arguments, then call it recursively.

function someFunc(&$res, array $keys, $data) {
    
    if (!empty($keys)) {
        $k = array_shift($keys);
        someFunc($res[$k], $keys, $data);
    }
    else $res = $data;
}

// call the function
$res = [];
someFunc($res, array('key1','key2', 'key3'), 'data');

echo $res['key1']['key2']['key3'];   //--> data
Edited by Barand
Link to comment
Share on other sites

There is a way to do it as you describe, so if you want that solution for academic reasons there's that. However it uses references (PHP does not have pointers but references are close) and I try to avoid references unless I know my audience (eg, coworkers) will be comfortable working with them.

 

For normal code I would go with either

a) The recursive version, as posted by Barand, or

b) A loop-based version where you construct the array backwards, as in

array()
array('key3' => array())
array('key2' => array('key3' => array()))
array('key1' => array('key2' => array('key3' => array())))
Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.