0

So My problem is:

  • I want to create nested array from string as reference.
  • My String is "res[0]['links'][0]"
  • So I want to create array $res['0']['links']['0']

I tried:

$result = "res[0]['links'][0]";
$$result = array("id"=>'1',"class"=>'3');
$result = "res[0]['links'][1]";
$$result = array("id"=>'3',"class"=>'9');

when print_r($res) I see:

<b>Notice</b>:  Undefined variable: res in <b>/home/fanbase/domains/fanbase.sportbase.pl/public_html/index.php</b> on line <b>45</b>

I need to see:

Array
(
    [0] => Array
        (
            [links] => Array
                (
                    [0] => Array
                        (
                            [id] => 1
                            [class] => 3
                        )

                )

        )
    [1] => Array
        (
            [links] => Array
                (
                    [0] => Array
                        (
                            [id] => 3
                            [class] => 9
                        )

                )

        )

)

Thanks for any help.

4
  • 1
    you want to print_r $res or $result ? Commented Feb 7, 2011 at 11:05
  • 2
    Why do you want to create an array from a string? Maybe it would be better to explain what you're trying to do at a high level, since its probable someone can suggest a better way of doing it (i.e. one that doesn't cause you to have an array in a string) Commented Feb 7, 2011 at 11:09
  • Those strings aren't even consistent with what you want in your array: surely the second $result should be "res[1]['links'][0]" instead of $result = "res[0]['links'][1]" Commented Feb 7, 2011 at 11:16
  • where did you get such strings? Commented Feb 7, 2011 at 11:27

4 Answers 4

1

So you have a description of an array structure, and something to fill it with. That's doable with something like:

function array_create(&$target, $desc, $fill) {

    preg_match_all("/[^\[\]']+/", $desc, $uu);
       // unoptimized, always uses strings

    foreach ($uu[0] as $sub) {
        if (! isset($target[$sub])) {
             $target[$sub] = array();
        }
        $target = & $target[$sub];
    }
    $target = $fill;
}

array_create( $res, "[0]['links'][0]", array("id"=>'1',"class"=>'3') );
array_create( $res, "[0]['links'][1]", array("id"=>'3',"class"=>'9') );

Note how the array name itself is not part of the structure descriptor. But you could theoretically keep it. Instead call the array_create() function with a $tmp variable, and afterwards extract() it to achieve the desired effect:

array_create($tmp, "res[0][links][0]", array(1,2,3,4,5));
extract($tmp);

Another lazy solution would be to use str_parse after a loop combining the array description with the data array as URL-encoded string.

Sign up to request clarification or add additional context in comments.

1 Comment

Nice! I added my example of use, in another answer to this question.
1

I have a very stupid way for this, you can try this :-) Suppose your string is "res[0]['links'][0]" first append $ in this and then put in eval command and it will really rock you. Follow the following example

$tmp = '$'.'res[0]['links'][0]'.'= array()';

eval($tmp);

Now you can use your array $res

100% work around and :-)

`

1 Comment

Well yes, that borders on being bad. It's only ever acceptable if such constructs originate from configuration files etc. Application input -even if meticulously filterd- should never be in there even partial. However still one of the few valid eval uses. +1
0
$res = array();
$res[0]['links'][0] = array("id"=>'1',"class"=>'3');
$res[0]['links'][0] = array("id"=>'3',"class"=>'9');

print_r($res);

but read the comments first and learn about arrays first.

Comments

0

In addition to mario's answer, I used another function from php.net comments, together, to make input array (output from jquery form serializeArray) like this:

[2] => Array
    (
        [name] => apple[color]
        [value] => red
    )

[3] => Array
    (
        [name] => appleSeeds[27][genome]
        [value] => 201
    )

[4] => Array
    (
        [name] => appleSeeds[27][age]
        [value] => 2 weeks
    )

[5] => Array
    (
        [name] => apple[age]
        [value] => 3 weeks
    )

[6] => Array
    (
        [name] => appleSeeds[29][genome]
        [value] => 103
    )

[7] => Array
    (
        [name] => appleSeeds[29][age]
        [value] => 2.2 weeks
    )

into

Array
(
    [apple] => Array
        (
            [color] => red
            [age] => 3 weeks
        )
    [appleSeeds] => Array
        (
            [27] => Array
                (
                    [genome] => 201
                    [age] => 2 weeks
                )
            [29] => Array
                (
                    [genome] => 103
                    [age] => 2.2 weeks
                )
        )
)

This allowed to maintain numeric keys, without incremental appending of array_merge. So, I used sequence like this:

function MergeArrays($Arr1, $Arr2) {
    foreach($Arr2 as $key => $Value) {
        if(array_key_exists($key, $Arr1) && is_array($Value)) {
              $Arr1[$key] = MergeArrays($Arr1[$key], $Arr2[$key]);
        }
        else { $Arr1[$key] = $Value; }
    }
    return $Arr1;
}
function array_create(&$target, $desc, $fill) {
    preg_match_all("/[^\[\]']+/", $desc, $uu);
    foreach ($uu[0] as $sub) {
        if (! isset($target[$sub])) {
              $target[$sub] = array();
        }
        $target = & $target[$sub];
    }
    $target = $fill;
}
$input = $_POST['formData'];
$result = array();
foreach ($input as $k => $v) {
    $sub = array();
    array_create($sub, $v['name'], $v['value']);
    $result = MergeArrays($result, $sub);
}

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.