MySQL/PHP: return two columns as an associative array as key => value pairs

陌路散爱 提交于 2020-01-07 05:45:43

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!