-1

Im trying to set the indexes of a 2d PHP array from numeric indexing to keys. What I have so far is :

$result = mysql_query("SELECT * FROM settings");
 if(mysql_num_rows($result) > 0 ){
        while($row = mysql_fetch_assoc($result)){
              $dataArray[] = $row ;
        }
}       

$value_to_display = $dataArray[0]['value'];

However, what I'd like to be able to use is something like this :

$value_to_display = $dataArray['some_index_value']['value'];

Anyone know how I can achieve this ? Ive tried replacing making a keys array and then using combine, but I can only do this manually. Any help is appreciated!

  • Please [stop using `mysql_*` functions](http://stackoverflow.com/questions/12859942/why-shouldnt-i-use-mysql-functions-in-php). [These extensions](http://php.net/manual/en/migration70.removed-exts-sapis.php) have been removed in PHP 7. Learn about [prepared](http://en.wikipedia.org/wiki/Prepared_statement) statements for [PDO](http://php.net/manual/en/pdo.prepared-statements.php) and [MySQLi](http://php.net/manual/en/mysqli.quickstart.prepared-statements.php) and consider using PDO, [it's really pretty easy](http://jayblanchard.net/demystifying_php_pdo.html). – Jay Blanchard Feb 09 '16 at 17:13
  • @JayBlanchard You're absolutely right, but for a complicated set of reasons I have to dig around in some old code, and can yet upgrade. – masterofimps Feb 09 '16 at 17:16
  • 1
    $dataArray[$row["anycolumn"]][] = $row ; – devpro Feb 09 '16 at 17:19
  • Why are you wanting to move these from one array to another? The first array `$row[]` seems to be perfectly acceptable unless you're trying to create an array of arrays. – Jay Blanchard Feb 09 '16 at 17:27

1 Answers1

2

How about

while ($row = mysql_fetch_assoc($result)) {
   $dataArray[$row['somefield']] = $row;
}

Assuming that somefield is unique, you'll get an array keyed by that field's values. If you need to key names to come from somewhere else, e.g.

$keynames = array('foo', 'bar', 'baz', ....);
$idx = 0;
while($row = mysql_fetch_assoc($result)) {
   $dataArray[$keynames[$idx]] = $row;
   $idx++;
}

just make sure you have enough keynames to handle all the records you get back from the query.

Marc B
  • 356,200
  • 43
  • 426
  • 500