问题
I apologize if this might have been asked before, or if this isn't even possible, but here is what I am hoping to get from a particular table using MySQL.
Say, I have the following table:
+-------------+------------------+
| property | value |
+-------------+------------------+
| style | unisex |
| color | blue |
| type | small |
+-------------+------------------+
I would like to be able to fetch the two columns property and value as an associative array from MySQL, so the end result would be:
array(
'style' => 'unisex',
'color' => 'blue',
'type' => 'small',
);
Just to provide context so people don't misinterpret what I'm asking:
I already know how I can do this using PHP once I have the result back from a generic SQL statement that would return each row's columns as key => value pairs. I was just wondering if it was possible to return one column's value as a key and the second value as the value to the key for each row from MySQL directly to continue with in PHP.
回答1:
There is no out of the box fetch mode that will give you an array indexed like that (how would it know which is the key? what if there's more than 2 columns?).
You can use PDO::FETCH_NUM and array_map() to build a new array, using the first column as key and the second as value:
<?php
$query = $db->prepare("SELECT property, value FROM table");
$query->execute();
$row = $query->fetchAll(PDO::FETCH_NUM);
$rowFormatted = array_map(function ($el) {
return [$el[0] => $el[1]];
}, $row);
var_dump($rowFormatted);
Sidenote: it looks like you're heading into an Entity-Attribute-Value antipattern. This will bring you problems along the road, so consider redesigning your schema. Take a look at this resources to learn more:
- https://www.slideshare.net/billkarwin/extensible-data-modeling
- https://martinfowler.com/bliki/UserDefinedField.html
- http://karwin.blogspot.cl/2009/05/eav-fail.html
来源:https://stackoverflow.com/questions/46815766/mysql-php-return-two-columns-as-an-associative-array-as-key-value-pairs