从PHP数组返回多个值

时间:2017-05-25 15:18:14

标签: php arrays multidimensional-array array-filter

如何过滤此数组中的每个数组以仅获取某些数据,例如tiduiddevice

我使用array_column只获取一条信息,但我怎样才能获得多条信息?

$object = $ticket->find();
$arr = json_decode(json_encode($object), true);
var_dump($arr);

以上代码片段返回数据数组。

array (size=2)
  0 => 
    array (size=9)
      'tid' => string '1' (length=1)
      'uid' => string '22' (length=2)
      'subject' => string 'iPhone 8' (length=8)
      'issue' => string 'iPhone 8 screen replacement' (length=27)
      'device' => string 'iPhone 8' (length=8)
      'created' => string '2017-05-25 00:01:11' (length=19)
      'identifier' => string '29cd54bf' (length=8)
      'status' => string 'New' (length=3)
      'tech' => string 'None' (length=4)
  1 => 
    array (size=9)
      'tid' => string '2' (length=1)
      'uid' => string '22' (length=2)
      'subject' => string 'iPhone 7' (length=8)
      'issue' => string 'iPhone 7 screen replacement' (length=27)
      'device' => string 'iPhone 7' (length=8)
      'created' => string '2017-05-25 00:27:42' (length=19)
      'identifier' => string 'b47f2c82' (length=8)
      'status' => string 'New' (length=3)
      'tech' => string 'None' (length=4)

预期输出:

array(2) {
    [0]=> array(3) {
        [0]=> string(1) "1"
        [1]=> string(2) "22"
        [2]=> string(8) "iPhone 8"
    }
    [1]=> array(3) {
        [0]=> string(1) "2"
        [1]=> string(2) "22"
        [2]=> string(8) "iPhone 7"
    }
}

3 个答案:

答案 0 :(得分:5)

这里我们使用array_map来实现所需的输出。

解决方案1:

Try this code snippet here

$array=array_map(function($value){
    return array($value["tid"],$value["uid"],$value["subject"]);
},$array);
print_r($array);

解决方案2:

Try this code snippet here

foreach($array as $value)
{
    $result[]=array($value["tid"],$value["uid"],$value["subject"]);
}
print_r($result);

答案 1 :(得分:0)

使用array_map

array_map(function($v){return [$v['tid'], $v['uid'], $v['device']];}, $array);

答案 2 :(得分:-1)

您可以使用双foreach循环来打印,然后打印出您喜欢的值。

foreach ($arr as $ar) {
    foreach ($ar as $key => $value) {
        if ($key == 'tid' | $key == 'uid' | $key == 'device') {
            echo $key . ': ' . $value;
        }
    }
}