2012-10-24 61 views
2

从风格数组:排序多维数组PHP

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 
     ) 

) 

任何帮助表示赞赏谢谢!

+0

$ styles数组是什么样的? –

+0

@PhillPafford刚刚更新了问题 – Benn

+0

数据如何进入您的样式数组?它来自文本吗? –

回答

5

假设你输入数组看起来像

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 
     ) 

) 
+0

魔法,让我旋转了一下:)但美丽! – Benn

+1

@Benn _Logic_,不_magic_ –

+0

谢谢你的解释! – Benn