Constructing multidimensional array in php

100 Views Asked by At

I need to construct this array:

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
      )
  )
)

And I am obtaining the following array:

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

I search the keys and values from a mysql_query. My error could be in array_key_exists or array_push, C1, C2, C3, C4....... are customers, I want that customers be keys, not values. The code is:

$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"]);
    }
}

Regards

1

There are 1 best solutions below

3
On

You can't have objects as keys.

But you could create a mapping array, that contains all your objects, where the key is some sort of unique id (like a SQL id or unique alias).