Dail
Dail

Reputation: 4606

How to convert this array using Hash Class in CakePHP?

I have this array:

array(
    (int) 0 => array(
        'region_id' => array(
            (int) 0 => '19'
            (int) 1 => '23'
        )
    )
)

I would like to transform it, in:

array(
    (int) 0 => array(
        'region_id' =>  '19'        
    ),
    (int) 1 => array(
        'region_id' =>  '23'        
    ),  
)

I read there is a magic class in cakephp (Hash).

Can I use it to transform the array or do I have to do it manually?

Upvotes: 0

Views: 143

Answers (2)

Andolasoft Inc
Andolasoft Inc

Reputation: 1296

Here is your required result, but yes i have used both cake Hash and manual php functions:

May you like this:

    $result = Hash::extract($foo, '{n}.region_id.{n}');
    $result = array_chunk($result,1);
    $required_result = array();
    foreach($result as $k => $v){
    foreach($v as $k1 => $v1){
      $required_result[$k]['region_id'] = $v1; 
    }       
    }
    pr($required_result);exit;

Upvotes: 0

Guillermo Mansilla
Guillermo Mansilla

Reputation: 3889

A good starting point is

$foo = array(
     0 => array(
                 'region_id' => array(
                     0 => 19,
                     1 => 23
                 )
             )
        );
debug(Hash::extract($foo, '{n}.region_id.{n}'));

Which returns

array(
    (int) 0 => (int) 19,
    (int) 1 => (int) 23
);

Your next job is to rename the array keys.

Upvotes: 1

Related Questions