简体   繁体   中英

Create a pure php assocative array from mysql data

I'm trying to create a php assocative array from mySql data where id is the key, so I can use that with array_key_exists . But problem is, the keys seem to be something else and not id . What needs to be done to make the array key id .

$conn = connect();
$stmt = $conn->prepare("select id, concat(type,status) as status from arraytest");
$stmt->execute();
$myArray = $stmt->fetchAll(PDO::FETCH_ASSOC);
print_r(($myArray));

Desired output

array("3"=>"00","6"=>"01");

Current Output

Array ( [0] => Array ( [id] => 3 [status] => 00 ) [1] => Array ( [id] => 6 [status] => 01 ) )

Sample table data:

"id"    "type"  "status"
"3"    "0"      "0"
"6"    "0"      "1"

Check the PDO::FETCH_KEY_PAIR constant.

PDO::FETCH_KEY_PAIR

Fetch a two-column result into an array where the first column is a key and the second column is the value. Available since PHP 5.2.3.
Source: http://php.net/manual/en/pdo.constants.php

You could do something like this:

foreach($myArray as $arr)
    $o[$arr['id']] = $arr['status'];

It loops trough your output creating a new array where ID is the key, and status is assigned as value.

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