简体   繁体   中英

PHP multi-dimensional array value as index

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) ) {
....
}

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!

更改查询并在末尾添加GROUP BY ID

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM