Note that there are some explanatory texts on larger screens.

plurals
  1. POdefining position in an array with string
    primarykey
    data
    text
    <p>I have an interesting problem... I am building an API where user specifies the location of some element in an array through string. Like this:</p> <pre><code>$path = "group1.group2.group3.element"; </code></pre> <p>Given this string, I must save some value to the correct place in an array. For the example above this would be:</p> <pre><code>$results['group1']['group2']['group3']['element'] = $value; </code></pre> <p>Of course, the code needs to be generic for whatever <code>$path</code> user throws at me. </p> <p>How would you solve this?</p> <p><strong>UPDATE - SOLUTION</strong>: using both ern0's (similar to my own) and nikc's answer as inspiration, this is the solution I decided on:</p> <pre><code>// returns reference to node in $collection as referenced by $path. For example: // $node =&amp; findnode('dir.subdir', $some_array); // In this case, $node points to $some_array['dir']['subdir']. // If you wish to create the node if it doesn't exist, set $force to true // (otherwise it throws exception if the node is not found) function &amp;findnode($path, &amp;$collection, $force = false) { $parts = explode('.', $path); $where = &amp;$collection; foreach ($parts as $part) { if (!isset($where[$part])) { if ($force) $where[$part] = array(); else throw new RuntimeException('path not found'); } $where =&amp; $where[$part]; } return $where; } $results = array(); $value = '1'; try { $bucket =&amp; findnode("group1.group2.group3.element", $results, true); } catch (Exception $e) { // no such path and $force was false } $bucket = $value; // read or write value here var_dump($results); </code></pre> <p>Thank you all for the answers, it was a nice exercise! :)</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload