0

aside from doing the actual work of iterating through an associative array, pushing a value into a new array and setting that equal the array of remaining fields, is there an array function built into PHP that would do something like this?

if so, what is it?

i would be changing the following:

Array
(
    [0] => Array
        (
            [0] => TEST    //Name (Database column name
            [1] => 12430   //ID (Database column name
            [2] => Y       //Save (Database column name
            [3] => 100    //Wert (Database column name
        )

into something like this:

Array
(
   [12430] => Array
           (
              [Name] => TEST
              [Save] => Y
              [Wert] => 100
           )

i work with while-loop:

....
while( $row = mysql_fetch_assoc($ergebnis) ) {
....
}
Marco
  • 35
  • 6
  • May be this will help http://stackoverflow.com/a/240676/2706988 – Rahil Wazir Apr 05 '14 at 22:42
  • 1
    Your first array is not really what fetch_assoc gives you … it’s rather the column names as keys and the column contents as value. So you’re nearly there already anyways … the rest is just a matter of taking the id value as index for your outer array, assigning the result of fetch_assoc to that … and then maybe unsetting the id key in the sub-array if you think that little redundancy actually does any harm. – CBroe Apr 05 '14 at 22:43

2 Answers2

0

I think that you are going to have to iterate through the array. There may be a function here that could shorten the code by about a line, but I doubt it will make a noticeable difference to the readability and efficiency of your code. So I would iterate through the array if I were your, quite short and simple.

$new_array = array();
while( $row = mysql_fetch_assoc($ergebnis) ) {
    $new_array[$row[1]] = $row;
    unset($new_array[$row[1]]);
}

Note that the mysql_ functions have been deprecated in PHP and you should be using mysqli_ or PDO instead, as it is more stable and secure.

Also, as @CBroe said, the mysql_fetch_assoc function will return the second part of your desired result already. The equivalent in PDO would be $query->fetch(PDO::FETCH_ASSOC);

Good luck!

Patrick Geyer
  • 1,515
  • 13
  • 30
0

Alter your query and add GROUP BY ID at the end.

ek9
  • 3,392
  • 5
  • 23
  • 34