CakePHP Hash class with method extract/combine

2019-07-28 12:59发布

问题:

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))));
}