在php中动态创建多维数组

时间:2013-11-25 19:00:33

标签: php arrays loops multidimensional-array

我从数据库中获取一些值,我需要动态创建一个多维数组,如下所示:

$found_data = 
array( 
    array('2011-11-02' => 'Mobile'),
    array('2011-11-02' => 'Mobile'),
    array('2011-11-04' => 'Mobile'),
    array('2011-11-08' => 'Desktop'),
    array('2011-11-08' => 'Mobile'),
    array('2011-11-08' => 'Mobile'),
    array('2011-11-08' => 'Mobile'),
    array('2011-11-15' => 'Mobile'),
    array('2011-11-18' => 'Mobile'),
    array('2011-11-21' => 'Desktop'),
    array('2011-11-23' => 'Mobile'),
    array('2011-11-28' => 'Desktop'),
    array('2011-11-30' => 'Mobile')
);

我正在考虑以下几点:

$found_data = array();

while($last_30_days_fetch = mysql_fetch_assoc($last_30_days_result))
{
    $hit_date = $last_30_days_fetch['hit_date'];
    $hit_device = $last_30_days_fetch['hit_device'];    
    array_push($found_data, array($clean_date=>$hit_device));

}

但是上述代码无法按预期工作。有什么想法吗?

//谢谢

3 个答案:

答案 0 :(得分:1)

您正在使用未定义的变量$ clean_date。检查你应该报告的error_reporting级别(未定义的变量)。

PHP允许使用[]语法将元素追加到数组中。

$found_data = array();

while($last_30_days_fetch = mysql_fetch_assoc($last_30_days_result))
{
    $found_data[] = array(
        $last_30_days_fetch['hit_date'] => $last_30_days_fetch['hit_device']
    );
}

答案 1 :(得分:0)

你能不能只使用:

$array[$hit_date] = $hit_device

答案 2 :(得分:0)

$found_data = array();

while($last_30_days_fetch = mysql_fetch_assoc($last_30_days_result))
{
    $found_data[] = array($last_30_days_fetch['hit_date']=>$last_30_days_fetch['hit_device']);
}

为什么过于复杂或者Dan说它把它放到一个单独的数组中就不需要多数组,除非你没有告诉我们其他的数据