0

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!

4

3 回答 3

3

基本上你想要的叫做数组采摘;这是一个将其引入语言的RFC ,但尚未被接受。

与此同时,你只需要用老式的方式来做:

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

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

// returns array(1, 2)

在 5.3 之前你必须这样写:

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

array_map('getid', $a);
于 2012-10-06T15:52:30.227 回答
1

我不确定我是否遵循您对数组设置的解释,但您正在寻找的函数可能是“array_keys”PHP 函数,它仅返回数组键。

如果这不是您正在寻找的答案,也许您可​​以通过使用正确的数组表示法来澄清您的问题,或者可能是数据库中的一个实际示例,指定您要隔离的值。

于 2012-10-06T15:48:34.127 回答
1

你的数组格式不清楚

选项 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);

选项 B

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

输出

array
  0 => string '1' (length=1)
  1 => string '2' (length=1)
  2 => string '3' (length=1)
于 2012-10-06T15:50:45.033 回答