PHP - 创建数组(mysql_fetch_array)程序时在数组中创建数组

时间:2016-05-05 23:04:29

标签: php arrays foreach while-loop

我想创建数组:

$branza_query = mysql_query ('SELECT craft FROM base') or die...   

 $craft = array();  
        while ($cra = mysql_fetch_array($craft_query))
        {
            $craft[] = $cra;
        }

没什么大不了的,但是当我想print_r它时,我会像以前一样:

Array ( [0] => Array ( [0] => steel [craft] => steel )
        [1] => Array ( [0] => farm [craft] => farm ) 
        [2] => Array ( [0] => some [craft] => some ) 
        [3] => Array ( [0] => it [craft] => it )    // etc.
      )

我只是想在现有数组中添加下一个值,结果如下:

Array ( [0] = steel
        [1] = farm
        [2] = some
        [3] = it        /etc.
      )

Array ( [0] = craft => steel
        [1] = craft => farm
        [2] = craft => some
        [3] = craft => it        /etc.
      )

或类似的东西,因为接下来的事情我想做的是:

foreach($craft as $value)
{
    echo '<option value ="'.$value.'"> '.$value.'</option>';
}

1 个答案:

答案 0 :(得分:0)

问题是,每次调用$cra时,您都会创建一个数组$craft[]=$cra作为其第一个元素,然后将其添加到$craft。这就是为什么你有一个三层数组。

但实际上,$cra已经是一个数组。所以你需要做的只是array_push($craft, $cra);。或者使用array_push($craft, $cra[0]);这将提供您想要的内容。

请参阅页面http://php.net/manual/en/function.mysql-fetch-array.php