当前位置:Gxlcms > PHP教程 > 这两种php数组的写法有何不同?

这两种php数组的写法有何不同?

时间:2021-07-01 10:21:17 帮助过:33人阅读

一:

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 );

人气教程排行