简体   繁体   中英

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?

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.

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM