排序多维数组PHP [英] Sort multidimensional array PHP
本文介绍了排序多维数组PHP的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
来自样式数组:
Array
(
[0] => style1|000000
[1] => style2|ff6600
)
我做了这个循环
foreach($styles as $key=>$value){
$sort_values[] = explode('|',$value);
}
**并使用print_r($ sort_values)我得到:**
** and with print_r($sort_values)I get:**
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
)
)
感谢您的任何帮助,谢谢!
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
)
)
这篇关于排序多维数组PHP的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文