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

问题描述 投票:0回答:1

我需要让我的阵列变得更好。我从数据库获取数据,我有里程碑和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
        )

)

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

php sql
1个回答
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来存储我们已经在里程碑上的信息,添加从查询中返回的不同“$ fase”可能更简洁的方法是使用两个不同的查询检索所有信息,一个用于里程碑,另一个用于里程碑为了fases

Edit2为里程碑式fases添加了一个子阵列

© www.soinside.com 2019 - 2024. All rights reserved.