从查询结果中构建一个多维数组

时间:2012-02-03 16:26:51

标签: php arrays

我有这样的代码输出类似:

    Array ( 
[0] => 15 
[1] => 13 
[2] => 16 
[3] => 16 

[4] => 10 
[5] => 10 
[6] => 13 
[7] => 13 
)    

但是,我想要这个结构:

    Array ( 
[0] => Array ( [0] =>  15, [1] =>  13, [2] =>  16, [3] =>  16) 
[0] => Array ( [0] =>  10, [1] =>  10, [2] =>  13, [3] =>  13) 
        ) 

这没有解决:$score[] = array($score_bd);。有什么想法吗?

php代码

$i =0;
        foreach ($arr_user_apply as $val) {
            $new_val = array($val);
            $arr[$i] = array_merge($str, $new_arr_tags_ids, $new_val, $new_id_oferta);

            $sql = $db -> prepare("
                query
                "
            );

            call_user_func_array(array($sql, "bind_param"), $arr[$i]);

            $sql -> execute();
            $sql -> bind_result($score_bd);

            while ($sql -> fetch()) {
                $score[] = $score_bd;
            };

            $i++;
        }

3 个答案:

答案 0 :(得分:0)

如果你只是想通过将密钥的键值放入新数组中来尝试向第一个数组添加另一个维度,那么这可能会起作用:

$firstArray = Array ( 0 => 15, 1 => 15, 2 => 13, 3 => 13, 4 => 16, 5 => 16, 6 => 10, 7 => 10, 8 => 13, 9 => 13, 10 => 6, 11 => 6 );
$newArray = Array();
foreach($firstArray as $key => $value)
{
  $newArray[] = Array($key => Array($value));
}
echo "<pre>";
print_r($newArray);
echo "</pre>";

编辑:

如果这个维度太深,那么试试这个:

$firstArray = Array ( 0 => 15, 1 => 15, 2 => 13, 3 => 13, 4 => 16, 5 => 16, 6 => 10, 7 => 10, 8 => 13, 9 => 13, 10 => 6, 11 => 6 );
$newArray = Array();
foreach($firstArray as $key => $value)
{
  $newArray[$key] =  Array($value);
}
echo "<pre>";
print_r($newArray);
echo "</pre>";

答案 1 :(得分:0)

$arr = array ( 0 => 15 ,1 => 15, 2 => 13, 3 => 13 ,4 => 16 ,5 => 16 ,6 => 10, 7 => 10);
foreach($arr as $key=>$value){
    $new_arr[$key][0] = $value;
}

答案 2 :(得分:0)

我不确定问题是否清楚,但这适用于我

            $score = array();
            while ($sql -> fetch()) {
                $score[] = $score_bd;
            };

            $new_score[] = array($score);


Array ( 
[0] => Array ( [0] => Array ( [0] => 15 [1] => 13 [2] => 16 ) ) 
[1] => Array ( [0] => Array ( [0] => 10 [1] => 13 [2] => 6 ) ) 
)