PHP:将数组附加到数组

时间:2014-03-13 10:08:42

标签: php arrays

首先,对不起,如果这听起来像是一个相当常见的问题,但是在没有找到令人满意的事情的情况下我看了一遍。

这是我的代码:

$query = mysql_query("SELECT * FROM Rezept");
            $allRecipes = array();
            for($i = 0; $i < mysql_num_rows($query); $i++){
                $average = 0;
                $row = mysql_fetch_row($query);
                $review = mysql_query("Select Stern FROM Bewertung WHERE Rezept_NR LIKE ". $row[0]);
                for($n = 0; $n < mysql_num_rows($review); $n++){
                    $stern = mysql_fetch_row($review);
                    $average += $stern[3];
                }
                $average /= mysql_num_rows($review);
                $recipe = array(
                    "Name" => $row[2],
                    "Kurzb" => $row[3],
                    "Bild" => $row[4],
                    "Bewertung" => $average
                );
                $allRecipes = array_merge_recursive($allRecipes, $recipe);
            }
            print_r($allRecipes);
}

反正。我得到了什么:

Array ( [Name] => Array ( [0] => Test [1] => Teeeest [2] => Test [3] => Test [4] => Test [5] => Test [6] => Test [7] => Test [8] => Test [9] => Test [10] => Test [11] => Test [12] => Test [13] => Test [14] => Tests [15] => Tests [16] => Tests ) [Kurzb] => Array ( [0] => Tes [1] => Testtest [2] => Test [3] => Test [4] => Test [5] => Test [6] => Test [7] => Test [8] => Test [9] => Test [10] => Test [11] => Test [12] => LOLTest [13] => Test [14] => Testersersts [15] => Testersersts [16] => Testersersts ) [Bild] => Array ( [0] => [1] => [2] => [3] => [4] => [5] => [6] => [7] => [8] => [9] => [10] => [11] => [12] => [13] => [14] => [15] => [16] => ) [Bewertung] => Array ( [0] => [1] => [2] => 0 [3] => [4] => [5] => [6] => [7] => [8] => [9] => [10] => [11] => [12] => [13] => [14] => [15] => [16] => ) ) 

它非常接近,但不是我想要的。

我想要的是什么:

Array([0] => array([Name] => Test [Kurzb] => Test [Bild] => something) [1] => array([Name] => Test [Kurzb] => Test [Bild] => something)) 

我是否尝试使用具有相同键的多个阵列? 我用错误的想法接受了这个吗?在编程方面,我是一个完整的新手......

2 个答案:

答案 0 :(得分:2)

使用array_combine进行此操作......

$a = array('green', 'red', 'yellow');
$b = array('avocado', 'apple', 'banana');
$c = array_combine($a, $b);

这将返回:

Array
(
    [green]  => avocado
    [red]    => apple
    [yellow] => banana
)

所以在你的代码中,改变一下:

$allRecipes = array_combine($allRecipes, $recipe);

答案 1 :(得分:0)

    $query = mysql_query("SELECT * FROM Rezept");
    $i =0;
    while(($result = mysql_fetch_row($query)) !== FALSE) 
    {
        $newArray[$i][] = $result; 
        $i++;
    }
    return $newArray;

1只是查询db 2用while获取它。