2017-10-12 43 views
0

我需要使阵列更好。 我正在从数据库获取数据,我有里程碑和milestone_parts。我想要二维数组。我需要第一个维度中的里程碑数据和第二个维度中的里程碑部分数据。PHP - 阵列不会变成二维阵列

有了这个代码:

$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

获取项目的ID,当前数组的项目组,根据此ID。 –

+0

请问你能更具体吗? – Haffoo

回答

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

+0

先生,这是行不通的: '$ fase = [];' '$ stone = [];' – Haffoo

+0

如果您正在运行一个旧的PHP版本,您只需要将“[]”替换为“数组()“ –

+0

我chnaged'$ fase = [];'到'$ fase = array();'但它没有改变结果。 – Haffoo