user1260310
user1260310

Reputation: 2227

php/mysql arrays strip out fields

I am running a query on a dbase that returns a multi-field recordset or array on fetch. The array is multi-field as I need several fields to output to the screen. However, I then want to save an array of just one variable, the id for each record. to compare against another list of records. So I need to, in effect, strip all but one field from the array.

In effect, I want to reduce (not using proper array notation):

{1 red dog, 2 orange cat, 3 yellow canary}

to

{1,2,3}

Is there an easy way to do this?

Thanks in advance!

Upvotes: 0

Views: 88

Answers (3)

Ja͢ck
Ja͢ck

Reputation: 173642

Basically what you want is called array plucking; here's an RFC to introduce this into the language, but it hasn't been accepted.

In the meantime you'd just have to do it the old fashioned way:

$a = array(
    array('id' => 1, 'title' => 'title1'),
    array('id' => 2, 'title' => 'title2'),
);

array_map(function($v) {
    return $v['id'];
}, $a);

// returns array(1, 2)

Before 5.3 you'd have to write it like so:

function getid($v)
{
    return $v['id'];
}

array_map('getid', $a);

Upvotes: 2

Baba
Baba

Reputation: 95141

Your array format is not clear

Option A

$array = array("1 red dog", "2 orange cat", "3 yellow canary");
$array = array_map(function($var){  $var = explode(" ", $var,2) ; return array_shift($var); }, $array);
var_dump($array);

Option B

$array = array("1" =>"red dog", "2" =>"orange cat", "3" =>"yellow canary");
$array = array_keys($array);
var_dump($array);

Output

array
  0 => string '1' (length=1)
  1 => string '2' (length=1)
  2 => string '3' (length=1)

Upvotes: 1

Ole Wolf
Ole Wolf

Reputation: 1431

I'm not sure I follow your explanation of the array setup, but maybe the function you're looking for is the "array_keys" PHP function, which returns the array keys only.

If this isn't the answer you're looking for, perhaps you could clarify your question by using the proper array notation, or possibly an actual example from your database specifying which value you're trying to isolate.

Upvotes: 1

Related Questions