CIRCLE
CIRCLE

Reputation: 4879

Multidimesional array pointers

I'm building an array piece by piece following a specific pattern.

For example, I have this string <val0=0, val1=<val2=2, val3=<val4=4>>, val5=5> and I need to translate it to an associative array. So every time I find < I have to create a new array and store the following elements until the next >.

The string above should result in something like this:

Array
(
    [val0] => 0
    [val1] => Array
        (
            [val2] => 2
            [val3] => Array
                (
                    [val4] => 4
                )

        )

    [val5] => 5
)

Everything is working fine for non-multidimensional arrays using str_split to break the string in pieces and iterating over them in a for loop but I'm having difficulties to find a workaround every time there is a nesting array in the string.

What I need is a way to have a pointer to the last created array inside the main array.

Is there a way to store an array pointer reference in a variable so I could do this:

print_r($MULTIARRAY['val1']['val3']);

// prints: array()

$pointer = pointer($MULTIARRAY['val1']['val3']);

$pointer[] = 'AAA';
$pointer[] = 'BBB';

print_r($MULTIARRAY['val1']['val3']);

// prints: array(
//   [0] => AAA
//   [1] => BBB
//)

Upvotes: 1

Views: 104

Answers (1)

Dmitry V.
Dmitry V.

Reputation: 336

Here you go, it's called reference

$a[1][22] = array();
$pointer = &$a[1][22];
$pointer[] = 3;
$pointer[] = 4;
print_r($a);

Upvotes: 1

Related Questions