php - PHP 多维数组排序

标签 php arrays

来自样式数组:

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

我做了这个循环

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

** 并使用 print_r($sort_values) 我得到:**

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

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

)

但我需要它是:

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

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

)

感谢任何帮助,谢谢!

最佳答案

假设您的输入数组如下所示

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

您的循环中需要更多的逻辑。

// 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
        )

)

关于php - PHP 多维数组排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13042018/

相关文章:

带有多个选项卡弹出警报的 Javascript session 超时

javascript - jquery ajax发送json

c - 从 C 中的另一个文件获取数组

c - 在 C 中,fgets 和 continue 跳过不止一行

PHP - 代码运行成功,但没有任何内容插入到数据库中

php - 我如何从 OpenCart 版本 1.5.1 中删除 index.php?route=common/home?

php - 我可以在类数组上使用 array_filter() 吗?

javascript - 数组中的每个字符都被 javascript 中的 ".hasOwnProperty(i)"识别为 Google Apps 脚本的 true

c++ - 对两个对应的数组进行排序

javascript - PHPStorm 配置 : How to remove background color on embedded html?