简体   繁体   中英

Sort multidimensional array PHP

from styles array :

Array
(
    [0] => style1|000000
    [1] => style2|ff6600
)

i made this this loop

foreach($styles as $key=>$value){
    $sort_values[] = explode('|',$value);
}

** and with print_r($sort_values)I get:**

Array
(
    [0] => Array
        (
            [0] => style1
            [1] => 000000
        )

    [1] => Array
        (
            [0] => style2
            [1] => ff6600
        )

)

But I need it to be :

Array
(
    [styles] => Array
        (
            [0] => style1
            [1] => style2
        )

    [links] => Array
        (
            [0] => 000000
            [1] => ff6600
        )

)

any help is appreciated thank you!

Assuming your input array looks like

array('style1|000000','style2|ff6600', 'style3|22ff22')

You need a little more logic in your loop.

// Initialize output array with an empty styles subarray and a links subarray
$out = array('styles'=>array(), 'links'=>array());
foreach ($styles as $key=>$value) {
   // Loop over and split on the |
   list($style, $link) = explode("|", $value);
   // And append the two resultant values to their respective subarrays via []
   $out['styles'][] = $style;
   $out['links'][] = $link;

   // list() is a useful construct for producing readable results with small arrays,
   // but I could also have used an array to receive the 
   // results of explode()
   // $split = explode("|", $value);
   // $out['styles'][] = $split[0];
   // $out['links'][] = $split[1];

}
print_r($out);

// Prints:
Array
(
    [styles] => Array
        (
            [0] => style1
            [1] => style2
            [2] => style3
        )

    [links] => Array
        (
            [0] => 000000
            [1] => ff6600
            [2] => 22ff22
        )

)

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