0

I have a sql query that, for each result returns a string like 1:One, 2:Two, 3:Three.

Now I want to convert each one of these strings to a PHP array like this:

Array(
    1: One,
    2: Two,
    3: Three
)

I know that I could do that with one explode function inside another one but, isn't that too much overkill if I have 500+ results on the mysql query? Is there any better way to get something like that?

Here is a sample of the mysql code that creates something like the string result that I gave:

GROUP_CONCAT(DISTINCT cast(concat(cast(number.id AS char),': ',number.name) AS char) order by number.id SEPARATOR ', ') AS all_active_numbers

EDIT

So here's an example of 2 possible returning rows from mysql:

|-----------------------------------------------------------------------|
|   id    |              all_groups            |     groups_assigned    |
|   1     |   1:Team A, 2:Team B, 3:Team C     |        1:Team A        |
|   2     |   1:Team A, 2:Team B, 3:Team C     |   2:Team B, 3:Team C   |
|-----------------------------------------------------------------------|

What I want to know is the best way to transform the strings of all_groups and groups_assigned of each row, into a PHP array. As I said, I know I could do it using 2 explode function (one inside another using foreach loops) but what if my query returns 500+ results? This seems like a big overkill for the server to compute explode's for each one of the 500+ rows.

Just to clarify, all_groups is something like the groups that are available for a person and groups_assigned is the groups where the person is registered from the available all_groups.

Another possibility is maybe divide this into 3 different queries?

4

1 回答 1

1

explode基于您的冒号,否则,形成您的查询以分别提供 KEY 和 VALUE。

PHP 示例(未经测试,仅作为示例):

$result = $pdo->query($query);
$myArray = array();
while($row = $result->fetchAll(PDO::FETCH_ASSOC)) {
  $myGroup = explode(": ", $row['all_active_numbers']);
  $myArray[][$myGroup[0]] = $myGroup[1];
}
var_dump($myArray);
于 2013-07-02T17:16:57.593 回答