Home  >  Q&A  >  body text

How to insert associative array in PHP?

I need to arrange the SQL results in PHP as follows:

if (!$result) {
  echo "An error occurred.\n";
  exit;
}

while($array = pg_fetch_array($result)) {
  $list = $array['list'];
}

pg_free_result($result);

But only pedro is returned in the array.

P粉762730205P粉762730205223 days ago459

reply all(1)I'll reply

  • P粉330232096

    P粉3302320962024-04-03 15:44:42

    You need pg_fetch_assoc() to get the returned associative array.

    And you need to build an array to append the nodes:

    $lists = [];
    while ($row = pg_fetch_assoc($result)) {
      $lists[] = $row['list'];
    }

    Or if you just want to play around, you can use pg_fetch_all_columns().

    https://www.php.net /manual/en/function.pg-fetch-all-columns.php

    $lists = pg_fetch_all_columns($result, 0);

    0 represents the first column in the row.

    reply
    0
  • Cancelreply