素材牛VIP会员
PHP数组变形的问题
 陈***丶  分类:ThinkPHP  人气:801  回帖:4  发布于6年前 收藏

从前 有这样一个数组

Array
(
    [id] => Array
        (
            [0] => 500002-016
            [1] => 500471-012
        )

    [name] => Array
        (
            [0] => 乐普国产药物支架(国产)[限额]
            [1] => 一次性正压无针连接式留置针(国产)[乙10%]
        )

    [specification] => Array
        (
            [0] => y
            [1] => x
        )

    [quantity] => Array
        (
            [0] => 22
            [1] => 23
        )

)

想要变成这样一个数组

Array
(
    [0] => Array
        (
            [id] => 500002-016
            [name] => 乐普国产药物支架(国产)[限额]
            [specification] => y
            [quantity] => 22
        )

    [1] => Array
        (
            [id] => 500471-012
            [name] => 一次性正压无针连接式留置针(国产)[乙10%]
            [specification] => x
            [quantity] => 23
        )
)

或者请问一下ThinkPHP的高手 第一种格式的数组怎样volist到视图的表格中去 各位有什么好办法么 先谢谢啦~

 标签:thinkphpphp

讨论这个帖子(4)垃圾回帖将一律封号处理……

Lv4 码徒
13***64 软件测试工程师 6年前#1
$data=你的数据;
$temp = array();//保存改变后的数据
foreach($data['id'] as $key=>$val){
    array_push($temp,array(
                              'id'=>$val,
                              'name'=>$data['name'][$key],
                              'specification'=>$data['specification'][$key],
                              'quantity'=>$data['quantity'][$key]
                          )
              );
}
unset($data);
Lv4 码徒
c2***31 交互设计师 6年前#2

这个。。。我想到的唯一办法也就是foreach了

function arr_format($arr) {
    $res = array ();
    foreach($arr as $k => $v) {
        foreach ($v as $kk => $vv) {
            $res[$kk][$k] = $vv;
        }
    }

    return $res;
}
Lv6 码匠
ti***nx 学生 6年前#3

来个不一样的,如果字段固定的话。

function arr_format($arr) {
    $result = array();
    list($id, $name, $specification, $quantity) = array_values($arr);
    for ($i = 0,$count = count($id);$i < $count;$i++) {
        $result[] = array(
            'id' => $id[$i],
            'name' => $name[$i],
            'specification' => $specification[$i],
            'quantity' => $quantity[$i]
        );
    }
    return $result;
}
Lv1 新人
真***溜 职业无 6年前#4

易理解的话,我会写成这样。

function rebuild($data)
{
	$result = array();
	$keys = array_keys($data);
	$num = count($data['id']);

	for ($i = 0; $i < $num; ++$i) {
		$item = array();
		foreach ($keys as $key) {
			$item[$key] = $data[$key][$i];
		}

		$result[] = $item;
	}

	return $result;
}
 文明上网,理性发言!   😉 阿里云幸运券,戳我领取