在PHP Array中选择某些数据

时间:2017-05-24 22:44:43

标签: php

使用这行代码时,我得到以下输出var_dump($ticket->find());如何只访问所有对象中的标识符?

我尝试var_dump($ticket->find()->identifier);但它返回null。

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

1 个答案:

答案 0 :(得分:0)

您可以使用array_maparray返回的find中的每个项目中选择所需的属性:

$filteredFields = array_map(function ($item) {
    // Return whatever properties you want here:

    return [$item->tid, $item->$uid, $item->issue];
}, $ticket->find());

$filteredFields将是array的{​​{1}}:

arrays

如果您只需要其中一个属性,则可能更容易使用array_column

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

这将返回如下内容:

$subjectFields = array_column($ticket->find(), "subject");

您还可以获取一个关联数组,指示哪个字段用作第三个参数的键:

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

这将返回:

$subjectsByTid = array_column($ticket->find(), "subject", "tid");