$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);
目前它正在返回:
Array ( [child1] => 165 [child2] => 165 [child3] => 164 )
但我希望它返回所有键和值,如果值不为空。
我实际上从表单中获取数据。 而我的实际代码是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>
这是表单发布数据。
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 )
答案 0 :(得分:1)
问题是数组键必须是唯一的,但您需要使用三个不同的值(child1
,167
和167
设置相同的键165
所以你每次只是覆盖相同的条目。
你能做的是:
$classes = array();
foreach ($arrays as $key=>$value) {
if($value != '') {
$exp= explode('_', $key);
$classes[$exp[0]][] = $exp[1];
}
}
将生成一个多维数组
答案 1 :(得分:1)
$arrays = array (
'child1_167'=>'1st',
'child1_167'=>'2nd',
'child1_165'=>'2nd',
'child2_165'=>'1st',
'child3_164'=>'2nd',
'child1_164'=>''
);
如果您在开头打印$ arrays,那么密钥是独一无二的,您将找到答案:
echo "<pre>";
print_r($arrays);
echo "</pre>";
答案 2 :(得分:1)
使用您在评论中提供的数组作为具有所有值的示例,将它们存储为二维关联数组:
$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);
这是输出:
Array
(
[child1] => Array
(
[1st] => 167
[2nd] => 164
)
[child2] => Array
(
[2nd] => 167
[1st] => 165
)
[child3] => Array
(
[2nd] => 165
[1st] => 164
)
)