使用对象PHP内部数组内的值查找数组中的对象键

时间:2017-03-05 13:54:17

标签: php arrays salesforce

我有一个像这样构建的对象数组(输出" var_dump()"调用我对这个问题进行了清理):

sObjects:array(3) {
  [0]=>
  object(SObject)#1 (2) {
    ["type"]=>
    string(9) "Course__c"
    ["fields"]=>
    array(1) {
      ["Id__c"]=>
      string(3) "111"
    }
  }  
  [1]=>
  object(SObject)#2 (2) {
    ["type"]=>
    string(9) "Course__c"
    ["fields"]=>
    array(1) {
      ["Id__c"]=>
      string(3) "222"
    }
  }
  [2]=>
  object(SObject)#3 (2) {
    ["type"]=>
    string(9) "Course__c"
    ["fields"]=>
    array(1) {
      ["Id__c"]=>
      string(3) "333"
    }
  }
}

现在,我要说$id = "111" 我将如何迭代我的对象数组并检索[id__c]的值等于$id的数组键? 例如,在这种情况下,我希望得到0

1 个答案:

答案 0 :(得分:2)

像这样使用array_filter:

$array = [
    [
    "type" => "Course__c",
    "fields" => ["Id_c" => "111"]
    ],
    [
    "type" => "Course__c",
    "fields" => ["Id_c" => "222"]
    ]
];

$result = array_filter($array,
    function($element) {
        return $element['fields']['Id_c'] == "111" ? true :false;
    });

print_r($result); 

将输出:

Array
(
    [1] => Array
    (
        [type] => Course__c
        [fields] => Array
            (
                [Id_c] => 111
            )

    )

    )
  • 对于Sobject版本,将$ element [' fields'] [' Id_c']替换为$ element->字段[' Id_c' ]

  • 此外,如果您想在回调函数中传递变量,请使用:

    $result = array_filter($array,
        function($element) use($externalVariable){
            return $element['fields']['Id_c'] == $externalVariable ? true :false;
    });
    
相关问题