这两种php数组的写法有何不同?
程序员文章站
2022-06-02 19:34:36
...
一:
while(!$param->end)
{
$param_array[$param->field['param_group_id']]['param_group_name'] = $param->field['param_group_name'];
$param_array[$param->field['param_group_id']]['values'][$param->field['param_id']]
= $param->field['param_name'];
$param->move_next();
}
二:
while(!$param->end)
{
$param_array[$param->field['param_group_id']] = array(
'param_group_name' => $param->field['param_group_name'],
'values' => array(
$param->field['param_id'] => $param->field['param_name']
)
);
$param->move_next();
}
while循环每次取$param->field中的一行数据,在第二中写法中$param_array['some_id']['values']数组中最终只有一个元素,不知道怎么回事?
回复内容:
一:
while(!$param->end)
{
$param_array[$param->field['param_group_id']]['param_group_name'] = $param->field['param_group_name'];
$param_array[$param->field['param_group_id']]['values'][$param->field['param_id']]
= $param->field['param_name'];
$param->move_next();
}
二:
while(!$param->end)
{
$param_array[$param->field['param_group_id']] = array(
'param_group_name' => $param->field['param_group_name'],
'values' => array(
$param->field['param_id'] => $param->field['param_name']
)
);
$param->move_next();
}
while循环每次取$param->field中的一行数据,在第二中写法中$param_array['some_id']['values']数组中最终只有一个元素,不知道怎么回事?
第二种写法每次都是重新定义 $param_aray[ $param->field['param_group_id'] ]
这个元素,当 $param->field['param_group_id']
重复的时候会造成对 $param_aray[ $param->field['param_group_id'] ]
的覆盖,看 DEMO 更清楚一点:
$data = array(
array("id"=> 1, "name"=>"a", "group"=>2, "value"=>10),
array("id"=> 2, "name"=>"b", "group"=>1, "value"=>11),
array("id"=> 3, "name"=>"c", "group"=>2, "value"=>12),
array("id"=> 4, "name"=>"d", "group"=>1, "value"=>13),
array("id"=> 5, "name"=>"e", "group"=>2, "value"=>14),
);
/* 第一种 */
$result = array();
foreach( $data as $item ) {
$result[ $item['group'] ]['value'][ $item['id'] ] = $item['value']
}
var_dump( $result );
/* 第二种 */
$result = array();
foreach( $data as $item ) {
$result[ $item['group'] ] = array(
"value" => array( $item['id'] => $item['value'] )
);
}
var_dump( $result );
上一篇: php array key 的储存规则
下一篇: 阿里云pypi软件包预警