¿Cómo se cambian las claves de índice de matriz a los valores de MySQL?

I need help working with arrays. I have an array of data from a MySQL query. After printing it in a for loop, I get the following array_flip:

    Array ( 

   [Duru 60] => 0 
   [Maxwell 50] => 1 
   [Fashanu 70] => 2 
   [Nwankwo 80] => 3 
   [Obi 0] => 4 

   ) 

The array value is a combination of 2 fields name and total score. What I want to achieve is an array like so:

   Array (

   [Duru 60] => 60 
   [Maxwell 50] => 50 
   [Fashanu 70] => 70 
   [Nwankwo 80] => 80 
   [Obi 0] => 0 

   )

What I want to achieve is to change the default array numeric keys (0,1,2,3,4) to total score obtained from the query.

Here is the code that gave the first array block:

PHP code begins

    $dataA = array();

    foreach($data as $key => $val){

$dataC = $val['lastname']." ".$val['total'];
array_push($dataA,($dataC));

     }
     $dataD = (array_flip($dataA));

     print_r($dataD);

preguntado el 31 de julio de 12 a las 15:07

3 Respuestas

$dataA = array();
foreach($data as $key => $val){
    $dataK = $val['lastname']." ".$val['total'];
    $dataV = $val['total'];
    $dataA[$dataK] = $dataV;
}
print_r($dataA);

Respondido 31 Jul 12, 15:07

this is wot i neec. U guys are the best. Will surely be back for more - user1565795

Prueba esto:

    $dataA = array();

    foreach($data as $key => $val){

           $dataC = $val['lastname']." ".$val['total'];

           $dataA[$dataC] = $val['total'];

     }

     print_r($dataA);

Respondido 31 Jul 12, 15:07

Array ( [60] => Duru 60 [Duru 60] => 0 [50] => Maxwell 50 [Maxwell 50] => 1 [70] => Fashanu 70 [Fashanu 70] => 2 [80] => Nwankwo 80 [Nwankwo 80] => 3 [0] => Obi 0 [Obi 0] => 4 ) - user1565795

¿Por qué no puedes simplemente hacer:

$newData = array();
foreach($data as $key => $val) {
  $newData[$val['lastname'] . ' ' . $val['total']] = $val['total'];
}
print_r($newData);

Respondido 31 Jul 12, 15:07

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.