将数组推送并附加到php中的关联数组中

时间:2013-03-31 06:07:40

标签: php

如何将数组推入“邻接”键值对中,该值对应具有包含“数组”的封装数组(即数组((“nodeTo”=>“$ to”),(“nodeTo”= >“$ to”)))而不覆盖它们并将它们添加为类似于“+ =”。同样,关键“邻接”的推进似乎并没有提升价值。

    $node[] = array(
        "adjacencies" => array(), //inside this array should go all the arrays seprated by commas.
        "data" => array(
                "color" => $color1,
                "type" => $type1 
            );

 // this push doesnt seem to detect the adjacencies value and doesnt really push the array inside of the container array. I also tried $node["adjacencies"][]=array("nodeTo" => "$to"); but it didnt work
    $node["adjacencies"]=array("nodeTo" => "$to");



}

2 个答案:

答案 0 :(得分:0)

顺便说一句,你在第二个陈述中使用$node我认为你的意思是:

$node = array(

$node[] = array(
//   ^^

然后你可以通过执行以下操作来推送数组:

$node['adjacencies'][] = array('nodeTo' => $to);

答案 1 :(得分:0)

如果你想要'adjacencies'内的多个数组,请将它们附加到数组的末尾:

$node[0]['adjacencies'][] = array("nodeTo" => "$to");

当然,您需要知道要使用哪个$node索引(如果有多个节点)。

修改

阅读完评论后,看起来OP所需的数组结构如下:

$node = array(
  'adjacencies' => array(),
  'data' => array(
    'color' => $color1,
    'type' => $type1,
  );
);

因此,要将其他节点附加到adjacencies数组,您可以执行以下操作:

$node['adjacencies'][] = array('nodeTo' => "$to");