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

Find object key in array using value inside an array inside the object PHP

我有一个像这样构建的对象数组("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.

像这样使用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->fields['Id_c']

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

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