开发者

Targeting a multi dimensional associative array part by index

How can I target a multi-dimensional associative array by index? I need to be able to do something along the lines of this...

$x=2;

$assoc_array = a开发者_Go百科rray(
"red" => array(1,2,3,4,5),
"green" => array(1,2,3,4,5),
"blue" => array(1,2,3,4,5)
);

array_push($assoc_array[$x],6);


You actually can do that. As an alternative, you can use $assoc_array[$x][] = 6

EDIT: The above is the answer for what you asked. The code below is for what I think you need, but didn't state clearly:

$x = 2;
$keys = array_keys($assoc_array);
var_dump($assoc_array[$keys[$x]]);

Working codepad example: http://codepad.org/QXfHmKH8


My proof that it works: http://codepad.org/G81fsTzl

Red being 0, green being 1, and blue being 2 or the $x=2 part.

If my answer is correct, be sure to check the checkbox to the left of this post so I can gain points. Points are what motivates me to continue to answer questions. Thank you for your time.

$x=2;

$assoc_array = array(
    "red" => array(1,2,3,4,5),
    "green" => array(1,2,3,4,5),
    "blue" => array(1,2,3,4,5)
);

$c = 0;
foreach ($assoc_array as $key => $value)
{
    if ($c == $x)
    {
        array_push($value, 6);
        $assoc_array[$key] = $value;
    }

    $c++;
}


You must reference them via the key which in this case is the colour values you have given. To add a new element to the first item (red) you would use:

$assoc_array["red"][] = 6;

Using $assoc_array[$x][] = 6; will create a new array key with the identifier of $x unless $x is either red, green or blue.

The above method works but is massively convoluted if you just wish to reference an existing array value.

Part of the idea of giving a string value as an array key is to allow the easy reference of the array values via a related string rather than a meaningless number.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜