1

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
  • I just tried that same example in my cakephp installation and worked fine using the Hash class and '{s}.name' Commented Dec 15, 2013 at 11:04

3 Answers 3

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Hash class was to be better!?
not getting you ? do you want to consider it in performance wise ?
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');
        });

Comments

-1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.