PHP - 数组不会变成二维数组

时间:2017-10-12 08:42:26

标签: php sql

我需要让我的阵列变得更好。 我从数据库获取数据,我有里程碑和milestone_parts。我想要二维数组。我需要第一个维度中的里程碑数据和第二个维度中的milestone_parts。

使用此代码:

$query = " 
         SELECT 
         a.id AS `milestone_id`, 
         a.titel AS `milestone_titel`, 
         a.client AS `client`,
         a.verkocht_id AS `milestone_verkocht_id`,

         b.id AS `milestonefase_id`, 
         b.titel AS `milestonefase_titel`,
         b.milestone_id AS `milestonefase_milestone_id`,
         b.omschrijving AS `milestonefase_omschrijving`
         FROM `milestones` a
         INNER JOIN `milestone_parts` b ON a.id=b.milestone_id
         WHERE a.verkocht_id = '99' 
         ";

         $result= $db->query($dbh, $query);


            while ($row = $db->fetchassoc($result))
            {
                $stone = array($row['milestone_verkocht_id'], $row['milestone_id'], $row['milestone_titel'], $row['client']);
                $fase = array($row['milestonefase_milestone_id'],$row['milestonefase_id'],$row['milestonefase_titel']);
                $stone[] = $fase;
                echo '<pre>'; print_r($stone); echo '</pre>';
            }

我得到了这个结果

Array
(
    [0] => 99
    [1] => 6
    [2] => string
    [3] => string
    [4] => Array
        (
            [0] => 6
            [1] => 10
            [2] => string
        )

)

Array
(
    [0] => 99
    [1] => 6
    [2] => string
    [3] => string
    [4] => Array
        (
            [0] => 6
            [1] => 11
            [2] => string
        )

)

但我需要(有名字):

Array
(
    [milestone_verkocht_id] => 99 // This is project id
    [milestone_id] =>  6
    [milestone_title] => string
    [client] => string
    [10] => Array
        (
            [milestonefase_milestone_id] => 6
            [milestonefase_id] =>  10
            [milestone_title] => string
        )
    [11] => Array
        (
            [milestonefase_milestone_id] =>  6
            [milestonefase_id] => 11
            [milestone_title] => string
        )
    [12] => Array
        (
            [milestonefase_milestone_id] => 6
            [milestonefase_id] => 12
            [milestone_title] => string
        )

)

你能帮助我或者你有解决方案吗?请帮帮我!

1 个答案:

答案 0 :(得分:0)

您可以循环查询返回的每个字段,检查字段名称并创建新数组

$stones = array();
while ($row = $db->fetchassoc($result)) {
    $fase = array();
    $stone = array('milestones' => array());
    foreach ($row as $k => $v) {
        if (strpos($k, 'milestonefase_') === 0) {
            $fase[$k] = $v;
        } else {
            $stone[$k] = $v;
        }
    }
    if(!isset($stones[$stone['milestone_id']])) {
      $stones[$stone['milestone_id']] = $stone;
    }
    $stones[$stone['milestone_id']]['milestones'][$fase['milestonefase_id']] = $fase;
}
echo '<pre>'.print_r($stones, true).'</pre>';

修改 进行了一些更改以匹配请求。现在我们使用$ stones来存储我们已经拥有的里程碑信息,并添加不同的&#34; $ fase&#34;从查询返回 可能更干净的方法是使用两个不同的查询检索所有信息,一个用于里程碑,另一个用于fases

<强> EDIT2 添加了里程碑fases的子数组