$arrays = array (
'child1_167'=>'1st',
'child1_167'=>'2nd',
'child1_165'=>'2nd',
'child2_165'=>'1st',
'child3_164'=>'2nd',
'child1_164'=>''
);
$classes = array();
foreach ($arrays as $key=>$value) {
if($value != '') {
$exp= explode('_', $key);
$classes[$exp[0]] = $exp[1];
}
}
print_r($classes);
currently it is returning like this:
Array ( [child1] => 165 [child2] => 165 [child3] => 164 )
but i want it to return all the keys and value if value is not blank.
I am actually getting the data from form. and my actual code is foreach ($_post as $key=>$value )
<td>
<select name="child1_<?php echo child_id(); ?>">
<option></option>
<option>1st</option>
<option>2nd</option>
</select>
</td>
<td>
<select name="child2_<?php echo child_id(); ?>">
<option></option>
<option>1st</option>
<option>2nd</option>
</select>
</td>
<td>
<select name="child3_<?php echo child_id(); ?>">
<option></option>
<option>1st</option>
<option>2nd</option>
</select>
</td>
and here is the form post data.
Array ( [child1_167] => 1st [child2_167] => 2nd [child3_167] => [child1_165] => [child2_165] => 1st [child3_165] => 2nd [child1_164] => 2nd [child2_164] => [child3_164] => 1st ) Array ( [167] => 2nd [165] => 2nd [164] => 1st )
Working with the array you provided in the comments her as an example that has all the values, storing them as a two-dimensional associative array:
$arrays = Array (
'child1_167' => '1st' ,
'child2_167' => '2nd' ,
'child3_167' => '',
'child1_165' => '',
'child2_165' => '1st' ,
'child3_165' => '2nd' ,
'child1_164' => '2nd' ,
'child2_164' => '',
'child3_164' => '1st' ,
) ;
$classes = array();
foreach ($arrays as $key=>$value) {
if($value != '') {
$exp= explode('_', $key);
$child_number=$exp[0];
$child_id=$exp[1];
$child_order=$value;
$classes[$child_number][$child_order] = $exp[1];
}
}
print_r($classes);
And this is the output:
Array
(
[child1] => Array
(
[1st] => 167
[2nd] => 164
)
[child2] => Array
(
[2nd] => 167
[1st] => 165
)
[child3] => Array
(
[2nd] => 165
[1st] => 164
)
)
The problem is that array keys must be unique, but you're setting the same key child1
with three different values (167
, 167
and 165
) so you're just overwriting the same entry each time.
What you could do is:
$classes = array();
foreach ($arrays as $key=>$value) {
if($value != '') {
$exp= explode('_', $key);
$classes[$exp[0]][] = $exp[1];
}
}
which will generate a multi-dimensional array
$arrays = array (
'child1_167'=>'1st',
'child1_167'=>'2nd',
'child1_165'=>'2nd',
'child2_165'=>'1st',
'child3_164'=>'2nd',
'child1_164'=>''
);
The key are uniques if you print $arrays on the begin you will find the answer:
echo "<pre>";
print_r($arrays);
echo "</pre>";