Chris
Chris

Reputation: 67

PHP / MySQL - Loading results into an array

I have a SQL query which returns a result of one field, so I have the following:

$article_id = $this->item->id;
$authors_default = mysql_query("SELECT multi_authors FROM jos_jxzine_articles WHERE id = '$article_id' LIMIT 1");
$authors_default = mysql_fetch_assoc($authors_default);
echo $authors_default['multi_authors'];

This echos out

128,129

and so on for different queries.

How can I make this into the following

array(128,129)

To then put into a prewritten function?

Cheers

Upvotes: 0

Views: 443

Answers (3)

Serge Stepanov
Serge Stepanov

Reputation: 588

$authors_array = explode(",", $authors_default['multi_authors']);

This will break apart your MySQL result into an array. Since your query pulls a string which is delimited by a comma, the explode() function can be used to separate out the string.

http://php.net/manual/en/function.explode.php

Upvotes: 0

jhine
jhine

Reputation: 247

Sorry, this is untested since I have removed PHP from my localhost. If I understand you correctly.

<?php $arr = explode(',', $authors_default['multi_authors']); print_r($arr); ?>

http://php.net/manual/en/function.explode.php

Upvotes: 0

user142162
user142162

Reputation:

The following code takes that MySQL row and splits it up into pieces using , as the delimiter. It then converts that array of strings to an array of integers.

$authors_arr = explode(',', $authors_default['multi_authors']);
// $authors_arr = array("128", "129");
$authors_arr = array_map('intval', $authors_arr);
// $authors_arr = array(128, 129);

You can then pass that array into a function like so:

myFunction($authors_arr); // Or however you have it setup.

Upvotes: 3

Related Questions