在私有函数上的数组上插入元素

时间:2016-01-07 14:28:27

标签: php zend-framework2 apigility

如何将元素插入到数组的最终位置,这个数组是在私有函数上?

private function getData()
{

    return array(
            1 => array(
                    'open_cookie_id' => 1,
                    'text' => 'I may throw up on ya',
                    'who'  => 'Leonard McCoy',
            ),
            2 => array(
                    'open_cookie_id' => 2,
                    'text' => 'I think these things are pretty safe.',
                    'who' => 'James T. Kirk'
            ),
            3 => array(
                    'open_cookie_id' => 3,
                    'text' => 'Well, I hate to break this to you, but Starfleet operates in space.',
                    'who' => 'James T. Kirk'
            ),
            4 => array(
                    'open_cookie_id' => 4,
                    'text' => 'Yeah. Well, I got nowhere else to go. The ex-wife took the whole damn planet in the divorce. All I got left is my bones.',
                    'who' => 'Leonard McCoy'
            ),
            5 => array(
                    'open_cookie_id' => 5,
                    'text' => 'If you eliminate the impossible, whatever remains, however improbable, must be the truth.',
                    'who' => 'Spock'
            )
    );

}

如何将元素6,7,8等插入到其他函数私有的这些函数的最终数组中 从这个功能:

  /**
     * Create a resource
     *
     * @param  mixed $data
     * @return ApiProblem|mixed
     */
    public function create($data)
    {
        //return new ApiProblem(405, 'The POST method has not been defined');
        //return $this->create($data) ;
        $adapter = new ArrayAdapter($this->getData());
        $adapter2 = Array
        (
            $data->open_cookie_id => array(
                                    'open_cookie_id'=>$data->open_cookie_id ,
                                    'text' =>$data->text, 
                                    'who' => $data->who
                                        )
        );

        $adapter2_converted = new ArrayAdapter($adapter2);
        //operation for merge two ArayAdapter ($adapter+$adapter2_convert)
       // $collection = new OpenCookieCollection($final_adapter);
        //return $collection;
    }

我正在使用php zend框架和apigility。

2 个答案:

答案 0 :(得分:3)

function 私有而不是array,因此您可以安全地使用已退回的array。请注意$adapterArrayAdapter数据类型,而不是简单的array,因此您无法轻松推送。

我的建议是向使用PHP ArrayAdapter的{​​{1}}添加一个方法,将您的数组添加到array_push()数据结构中并使用如下所示: ArrayAdapter

答案 1 :(得分:1)

我认为这是您实际调用私有方法getData()的行:

$adapter = new ArrayAdapter($this->getData());

如果你需要的只是一个添加了一些额外元素的数组,你可以这样做:

$data = $this->getData();
$data[] = 'more data';
$data[] = 'even more data';
$adapter = new ArrayAdapter($data);