0

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

3 Answers 3

1
$dataA = array();
foreach($data as $key => $val){
    $dataK = $val['lastname']." ".$val['total'];
    $dataV = $val['total'];
    $dataA[$dataK] = $dataV;
}
print_r($dataA);
Sign up to request clarification or add additional context in comments.

1 Comment

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

Try this:

    $dataA = array();

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

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

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

     }

     print_r($dataA);

1 Comment

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

Why can't you just do:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.