Drongo_III Posted November 14, 2015 Share Posted November 14, 2015 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 Quote Link to comment https://forums.phpfreaks.com/topic/299481-set-associative-array-at-pointer/ Share on other sites More sharing options...
Barand Posted November 14, 2015 Share Posted November 14, 2015 (edited) 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 November 14, 2015 by Barand Quote Link to comment https://forums.phpfreaks.com/topic/299481-set-associative-array-at-pointer/#findComment-1526391 Share on other sites More sharing options...
requinix Posted November 15, 2015 Share Posted November 15, 2015 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()))) Quote Link to comment https://forums.phpfreaks.com/topic/299481-set-associative-array-at-pointer/#findComment-1526443 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.