0

Having a hard time figuring out how to explain it, so maybe the code will help.

$out = array();

source_addValue($out['sources']['site1']['user_id'], '12345');
source_addValue($out['sources']['site1']['username'], 'testuser');
source_addValue($out['sources']['site1']['address']['state'], 'CA');

function source_addValue($field, $value) {
    global $out;
    if (!$field) $field = $value;
}

That, or since the $out['sources'] part remain the same, maybe something like:

$out = array();

source_addValue('site1', 'user_id', '12345');
source_addValue('site1', 'username', 'testuser');
source_addValue('site1', array('address','state'), 'CA');

function source_addValue($site, $field, $value) {
    global $out;
    if (!$out['sources'][$site]$field) $out['sources'][$site]$field = $value;
}

Either way, I'm getting hung up on the function, and specifically the if statement. I just need to be able to check to see if that array value has been set for $out (with the ability to check sub-arrays) and if it isn't, add it to the $out array.

1

2 Answers 2

2

I'm not confident I understand what you wan't, but I'll guess:

function autoVivifyDynamicKeyPath($pathKeys, $val) {
    global $out;
    $cursor =& $out;
    foreach ($pathKeys as $key) {
        if (!isset($cursor[$key]) || !is_array($cursor[$key])) {
            $cursor[$key] = array();
        }
        $cursor =& $cursor[$key];
    }
    $cursor = $val;
}
autoVivifyDynamicKeyPath(array('site1', 'address', 'state'), 'ca');
Sign up to request clarification or add additional context in comments.

Comments

0

Rambo's function doesn't check whether the current key has been set or not. It overwrites all keys that already have a value. Here's a modified version that checks for keys already present

$out = array();

source_addValue(array('sources', 'site1', 'user_id'), '12345');
source_addValue(array('sources', 'site1', 'username'), 'testuser');
source_addValue(array('sources', 'site1', 'address', 'state'), 'CA');

function source_addValue($pathKeys, $val) {
    global $out;
    foreach ($pathKeys as $key) {
        if (!isset($out[$key]) && !is_array($out[$key])) {
            $out[$key] = array();
        }
        $out =& $out[$key];
    }
    if(empty($out)){
        $out = $val;
    }
}

print_r($out);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.