1

Spending a while on it now, I can't figure out how to achieve this:

I want to use an array as caching some data. To find the items quickly, i want to use keys.

Let's say I have following data in the array:

$cache = [
'User' =>
  ['name' =>
   [ 'firstname' => 'John',
     'lastname' => 'Doe'
   ],
  'email' => 'john@doe.com'
        ],
        'Language' =>
                ['code' => 'en',
                'region' => 'UK'
        ]
];

In my situation I want to add a key to User, his nickname. So $cache should look like this:

$cache = [
  'User' =>
    ['name' =>
        [ 'firstname' => 'John',
          'lastname' => 'Doe',
          'nickname' => 'Demogorgon'
        ],
      'email' => 'john@doe.com'
    ],
  'Language' =>
    ['code' => 'en',
     'region' => 'UK'
    ]
];

How can i create a function like: addToCache(array &$cache, array $keyCollection, $value) : void;

So a function call should be something like: addToCache($cache, ['User', 'name', 'nickname'], 'Demogorgon');

The code I have now:

function addT(array &$ses, array $keys, $value, int $level = 0)
{
    $currentKey = $keys[$level];
    $isLastKey = $level === (count($keys) - 1);


    if (array_key_exists($currentKey, $ses) === true) {

        if ($isLastKey === true) {
            $ses[$currentKey] = $value;
            return $ses;
        } else {
            return addT($ses[$currentKey], $keys, $value, $level + 1);
        }
    } else {
        if ($isLastKey === true) {
            $ses[$currentKey] = $value;
            return $ses;
        } else {
            $ses[$currentKey] = array();
            return addT($ses[$currentKey], $keys, $value, $level + 1);
        }
    }
}

Thanks in advance!

-- update => I've tested the suggestions below, but ran into a problem with $keysz: "Warning: Illegal string offset 'suffix'" => Fatal error: Uncaught Error: Cannot create references to/from string offsets.

    function set($path, &$array=array(), $value=null) {
    //$path = explode('.', $path); //if needed
    $temp =& $array;

    foreach($path as $key) {
        $temp =& $temp[$key];
    }
    $temp = $value;
}

$cache = [
            'User' =>
                [
                    'name' =>
                        [
                            'firstname' => 'John',
                            'lastname' => 'Doe'
                        ],
                    'email' => 'john@doe.com'
                ],
            'Language' =>
                [
                    'code' => 'en',
                    'region' => 'UK'
                ]
];

$keysx = array('User', 'name', 'nickname');
$keysy = array('User', 'name', 'firstname');
$keysz = array('User', 'name', 'lastname', 'suffix');


set($keysx, $cache, 'Demogorgon');
echo '<pre>';
var_dump($cache);
echo '</pre>';

set($keysy, $cache, 'newFirstName');
echo '<pre>';
var_dump($cache);
echo '</pre>';

set($keysz, $cache, 'senior');

0 Answers0