CakePHP Hash class with method extract/combine

回眸只為那壹抹淺笑 提交于 2019-12-24 13:42:24

问题


What is solution of extract to array

I have array:

$arr = array(
    'key1' => array(
        'name' => 'Value 1'
    ),
    'key2' => array(
        'name' => 'Value 2'
    )
);

I would like get results like this:

Array
(
    [key1] => Value 1
    [key2] => Value 2
)

In Cake 2.2 and lower works by Set::extract('{\w+}.name', $arr) but when I would like use Hash by Hash::extract($arr, '{\w+).name') the results not corectly (also Hash::extract($arr, '{s}.name') return incorect.

How do this using new Hash class?


回答1:


just a follow up on @Anil kumar's answer

in case one of your result set returns an empty array, this would prevent an undefined index break:

$arr = Hash::map($arr, '', function($newArr) {
          return Hash::get($newArr, 'name');
        });



回答2:


Try this.

$arr = array(
    'key1' => array(
        'name' => 'Value 1'
    ),
    'key2' => array(
        'name' => 'Value 2'
    )
);

$arr = Hash::map($arr, '', function($newArr) {
    return $newArr['name'];
});

Now $arr will be:

Array
(
    [key1] => Value 1
    [key2] => Value 2
)

Hope this helps you.




回答3:


try this

    function admin_get_city() {
        $this->layout = 'ajax';
        $country_id = $this->request->data['Company']['country_id'];
    $city_id = $this->Company->find('all', array('conditions' => array('Company.country_id' => $country_id)));
    $cities_id = Hash::extract($city_id, '{n}.Company.city_id'); /*         * Hash::extract will Extarct language_id from array* */
    $this->set('city', $this->City->find('list', array('conditions' => array('City.country_id' => $country_id))));
}


来源:https://stackoverflow.com/questions/20244316/cakephp-hash-class-with-method-extract-combine

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!