将数组追加到特定的数组元素

时间:2014-02-03 20:23:21

标签: php arrays

我目前有这个array结构,我稍后将其转换为JSON

Array
(
    [response] => Array
        (
            [timestamp] => 1391457939
            [crimes] => Array
                (
                    [year] => 6-2013
                )
        )
)

我想知道是否有一种方法可以将数组数据附加到选定的数组节点,而无需指定根数组节点。例如,我想将以下array附加到上面的crimes数组中:

array(
    "Robbery" => 123,
    "Burglary" => 456
);

所以看起来应该是这样的:

Array
(
    [response] => Array
        (
            [timestamp] => 1391457939
            [crimes] => Array
                (
                    [year] => 6-2013
                    [Robbery] => 123 //Appended Data
                    [Burglary] => 456 //Appended Data
                )
        )
)

功能:

    public function addDataToJSONResp($parentArrayName, $arrayData){

        //jsonResponse is the main array which currently holds the array data which will be converted into JSON at a later step.
        if(isset($this->jsonResponse)){
            //Do processing here
            //Search for parent array node in jsonResponse.
            //append $arrayData to jsonResponse if it finds the parent array element.
        }else{
            //error
        }
    }

使用的功能:

    private function addDataToJSONResp($nodeName, &$array, $data) {
       foreach ($array as $key => $val) {

           if ($key == $nodeName) {

               foreach($data as $k => &$v){
                    $array[$key][$k] = $v;
                }

           }else if(is_array($val)){
                $this->addDataToJSONResp($nodeName, $val, $data);
           }
       }
    }

2 个答案:

答案 0 :(得分:0)

您可以在变量中存储对子数组的引用:

$root = array(
    'response' => array(
        'timestamp' => 1391457939,
        'crimes' => array(
            'year' => '6-2013'
        )
     )
);

$crimes = &$root['response']['crimes'];

现在,每当您对$crimes进行更改时,它都会反映在$root中。

为了追加数组:

array(
    "Robbery" => 123,
    "Burglary" => 456
);

然后你可以这样做:

$crimes = array_merge($crimes, array(
    "Robbery" => 123,
    "Burglary" => 456
));

可替换地:

$crimes['Robbery'] = 123;
$crimes['Burglary'] = 456;

输出

Array
(
    [response] => Array
        (
            [timestamp] => 1391457939
            [crimes] => Array
                (
                    [year] => 6-2013
                    [Robbery] => 123
                    [Burglary] => 456
                )

        )

)

这是demonstration,在ideone.com上托管。

答案 1 :(得分:0)

这是你想要达到的目标吗?

<?php


/**
 * We're passing the $inputArray in as reference
 * since we want the passed array to be changed 
 * right away
 *
 * $dataArray is the array we want to append
 *
 * $node, is the array key of the array we want our data 
 * to append on
 **/

function pushToNode(&$inputArray, $dataArray, $node)
{
    // Traverse our Input array
    foreach($inputArray AS $key => &$value)
    {
        // If the key of the current iteration
        // matches the node we want to append
        // our data on, we're done.
        if($key === $node){
            // We just iterate trough our data array...
            foreach($dataArray AS $k => &$v)
            {   
                // and append the keys and the values 
                // to the array we wanted to.
                $inputArray[$key][$k] = $v;
            }
            return;
        }
        // Since you don't want to specify the root node
        // our function needs to be recursive
        if(is_array($value))
        {
            pushToNode($value, $dataArray, $node);
        }
    }
}

$myArray = [

    'response' => [
        'timestamp' => 1293845329,
        'crimes' => [
            'year' => '1995'
        ]
    ]

];

$crimes = [
    'robbery'  => 'I robbed someone, wow!',
    'burglary' => 'Oh look. Catch me if you can.'
];

pushToNode($myArray, $crimes, 'crimes');

echo "<pre>";
print_r($myArray);
echo "</pre>";

<强>输出:

Array
(
    [response] => Array
        (
            [timestamp] => 1293845329
            [crimes] => Array
                (
                    [year] => 1995
                    [robbery] => I robbed someone, wow!
                    [burglary] => Oh look. Catch me if you can.
                )

        )

)

重要的代码被注释,但基本上我们是递归地遍历输入数组。如果我们在节点上,我们想要附加我们的数据,我们追加它并返回。我们的输入数组作为参考传入,因此数组本身将被更改。