简体   繁体   中英

Converting Multiple array into Single array

I'm having quite hard time to figure out how can i convert this into single array based on cakephp. I'm new in cakephp and still learning. I hope you guys could help me.

'Sizes' => array(
            'girls' => ['7-8', '8', '9-10', '10', '11-12', '12', '13-14'],
            'bras' => ['32A', '32B', '32C', '32D', '34A', '34B', '34C', '34D', '34DD', '36A', '36B', '36C', '36D', '36DD', '38A', '38B', '38C', '38D', '38DD', '40A', '40B', '40C', '40D', '40DD'],
            'size' => ['32', '34', '36', '38', '40', '42', '44', '46', 'XS', 'S', 'M', 'L', 'XL', 'XXL', '2XL', 'XXXL'],
        )
$new_array = [];

foreach($Sizes as $v){

    $new_array += $v;

}
echo '<pre>';
print_r($new_array);

I just did it like this and it work

'Sizes' => array(
            'size' => [
                '7-8', '8', '9-10', '10', '11-12', '12', '13-14',
                '32A', '32B', '32C', '32D', '34A', '34B', '34C', '34D', '34DD', '36A', '36B', '36C', '36D', '36DD', '38A', '38B', '38C', '38D', '38DD', '40A', '40B', '40C', '40D', '40DD', 
                '32', '34', '36', '38', '40', '42', '44', '46', 'XS', 'S', 'M', 'L', 'XL', 'XXL', '2XL', 'XXXL'
            ],
        )

You could that using array_merge function. But since PHP version 7.4 you can do that using spread operator easily. But you may use loop to do that too. See the following examples:

<?php

$a = array(
        'Sizes' => array(
            'girls' => ['7-8', '8', '9-10', '10', '11-12', '12', '13-14'],
            'bras' => ['32A', '32B', '32C', '32D', '34A', '34B', '34C', '34D', '34DD', '36A', '36B', '36C', '36D', '36DD', '38A', '38B', '38C', '38D', '38DD', '40A', '40B', '40C', '40D', '40DD'],
            'size' => ['32', '34', '36', '38', '40', '42', '44', '46', 'XS', 'S', 'M', 'L', 'XL', 'XXL', '2XL', 'XXXL'],
        )
    );

// Method 1: (since 7.4)    
$b = [...$a['Sizes']['girls'], ...$a['Sizes']['bras'], ...$a['Sizes']['size']];

var_dump($b);

// Method 2:
$c = array_merge($a['Sizes']['girls'], $a['Sizes']['bras'], $a['Sizes']['size']);

var_dump($c);

// Method 3:
$d = $a['Sizes']['girls'] + $a['Sizes']['bras'] + $a['Sizes']['size'];

var_dump($d);

Note:

  • The + operator makes union of the two arrays.
  • The array_merge function makes union but the duplicate keys are overwritten.

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