CakePHP Hash类,带方法提取/组合

时间:2013-11-27 13:53:07

标签: cakephp hash extract

什么是提取物到阵列的解决方案

我有阵列:

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

我希望得到这样的结果:

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

在Cake 2.2和Lower Set::extract('{\w+}.name', $arr)下工作,但是当我希望Hash::extract($arr, '{\w+).name')使用Hash时,结果不是核心的(Hash::extract($arr, '{s}.name')也会返回incorect。

如何使用新的Hash类?

3 个答案:

答案 0 :(得分:2)

试试这个。

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

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

现在$arr将是:

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

希望这会对你有所帮助。

答案 1 :(得分:1)

只需跟进@Anil kumar的回答

如果您的一个结果集返回一个空数组,这将阻止未定义的索引中断:

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

答案 2 :(得分:-1)

试试这个

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