在php中构造多维数组

时间:2014-01-08 17:56:01

标签: php arrays multidimensional-array array-push array-key-exists

我需要构造这个数组:

Array(
  [Creativo] => Array(
      [C1] => Array(
        [0] => O10
        [1] => O11
      )
      [C2] => Array(
        [0] => O12
        [1] => O13
        [2] => O14
      )
  )
  [Detallista] => Array(
      [C3] => Array(
        [0] => O15
        [1] => O16
        [2] => O17
      )
      [C4] => Array(
        [0] => O18
        [1] => O19
      )
  )
  [Emprendedor] => Array(
      [C5] => Array(
        [0] => O20
      )
      [C6] => Array(
        [0] => O21
      )
  )
)

我正在获取以下数组:

Array(
  [Creativo] => Array(
     [0] => C1
     [1] => C2
  )
  [Detallista] => Array(
     [0] => C3
     [1] => C4
  )
  [Emprendedor] => Array(
     [0] => C5
     [1] => C6
  )
)

我从mysql_query中搜索键和值。我的错误可能在array_key_exists或array_push,C1,C2,C3,C4 .......是客户,我希望客户是关键,而不是价值观。代码是:

$tagsTree = array();
$customersTree = array();
$queryResult = mysql_query("SELECT T.name AS Etiqueta, C.id AS Cliente, O.id AS Pedido, O.total AS Total
                                                                    FROM `Tag` T 
                                                                    JOIN CustomerTag CT ON T.name=CT.tagName LEFT JOIN Customer C ON CT.customerId=C.id LEFT JOIN `Order` O ON C.id=O.customerId") or die('Error al consultar los pedidos asociados a los clientes etiquetados: '.mysql_error());;

while($treeDB = mysql_fetch_assoc($queryResult)){
    if(empty($treeDB)){
    }
    else{
        if(!array_key_exists($treeDB["Etiqueta"], $tagsTree)){
            $tagsTree[$treeDB["Etiqueta"]] = array();
        }
        if(!array_key_exists($treeDB["Cliente"], $customersTree)){
            $customersTree[$treeDB["Cliente"]] = array();
        }
        array_push($tagsTree[$treeDB["Etiqueta"]], $treeDB["Cliente"]);
        array_push($customersTree[$treeDB["Cliente"]], $treeDB["Pedido"]);
    }
}

此致

1 个答案:

答案 0 :(得分:0)

您不能将对象作为键。

但您可以创建一个包含所有对象的映射数组,其中键是某种唯一ID(如SQL id或唯一别名)。