我有以下多维数组(这只是一个提取),并且想动态创建一组一维数组并添加值。
我有什么:
0 =>
0 => Image
1 => DE
2 => Hamburg-S02-I01
3 => 54
4 => Button
1 =>
0 => Image
1 => GB
2 => London-S01-I01
3 => 51
4 => Button
2 =>
0 => Image
1 => GB
2 => London-S01-I04
3 => 60
4 => Button
3 =>
0 => Image
1 => DE
2 => Berlin-S02-I01
3 => 57
4 => Button
4 =>
0 => Image
1 => DE
2 => Hamburg-S02-I01
3 => 52
4 => Button
我需要什么:
$Hamburg = array('Hamburg-S02-I01', 'Hamburg-S02-I01');
$London= array('London-S01-I01', 'London-S01-I04');
$Berlin= array('Berlin-S02-I01');
感谢您的帮助!谢谢!
答案 0 :(得分:1)
这样的事可能有用:
$cities = array();
foreach($images as $image) {
$parts = explode('-',$image[2]);
$city = $parts[0];
if(!isset($cities[$city])) $cities[$city] = array();
$cities[$city][] = $image[2];
}
答案 1 :(得分:0)
试试这个... $myarray
是一个包含上述示例的数组。
$cities = array();
foreach($myarray as $key => $val){
unset($tmp);
$tmp = explode("-",$val[2]);
if(!is_array($cities[$tmp[0]])){
$cities[$tmp[0]] = array();
}
array_push($cities[$tmp[0]], $val[2]);
}
我......
循环播放原始阵列。
使用变量$tmp
将元素拆分为城市名称。
只使用城市名称,我测试是否有一个具有该名称的新数组元素。
如果没有,请在$cities
内创建该数组。
无论哪种方式,将城市字符串推入城市阵列。
答案 2 :(得分:0)
$new_array = array();
foreach ($array as $key => $val) {
$new_array[explode('-',$val[2])[0]][] = $val;
}
该代码遍历您的数组 - 我任意命名$array
- 并将其中的每个sub_array推入另一个数组中的sub_arrays中,该键将是原始sub_array的第三个条目中的第一个连字符之前的任何内容。我不知道这是不是你所追求的,但至少它会激励你。
新阵列的内容:
(3)
[Hamburg] => (2)
[0] => (5)
[0] => Image
[1] => DE
[2] => Hamburg-S02-I01
[3] => 54
[4] => Button
[1] => (5)
[0] => Image
[1] => DE
[2] => Hamburg-S02-I01
[3] => 52
[4] => Button
[London] => (2)
[0] => (5)
[0] => Image
[1] => GB
[2] => London-S01-I01
[3] => 51
[4] => Button
[1] => (5)
[0] => Image
[1] => GB
[2] => London-S01-I04
[3] => 60
[4] => Button
[Berlin] => (1)
[0] => (5)
[0] => Image
[1] => DE
[2] => Berlin-S02-I01
[3] => 57
[4] => Button
$new_array = array();
foreach ($array as $key => $val) {
$new_array[explode('-',$val[2])[0]][] = $val[2];
}
第二个版本仅推送第三个条目,因为它似乎就是你所追求的。
输出:
(3)
[Hamburg] => (2)
[0] => Hamburg-S02-I01
[1] => Hamburg-S02-I01
[London] => (2)
[0] => London-S01-I01
[1] => London-S01-I04
[Berlin] => (1)
[0] => Berlin-S02-I01