khofm khofm - 3 years ago 65
PHP Question

How to create new arrays from existing multidimensional array in PHP

I have the following multi-dimensional array (this is only an extract) and would like to dynamically create a set of one-dimensional arrays and add values.

What I have:

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


What I need:

$Hamburg = array('Hamburg-S02-I01', 'Hamburg-S02-I01');
$London= array('London-S01-I01', 'London-S01-I04');
$Berlin= array('Berlin-S02-I01');


I appreciate your help! Thanks!

Answer Source
$new_array = array();
foreach ($array as $key => $val) {
    $new_array[explode('-',$val[2])[0]][] = $val;
}

That code travels through your array - that I arbitrarily named $array - and push every sub_array in it inside sub_arrays in another array which key will be whatever is before the first hyphen character in the third entry of the original sub_array. I don't know if it's what you were after, but maybe at least it will inspire you.

Content of new 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];
}

The second version pushes only the third entry, since it seems that's what you're after.

Output : (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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download