+ Start a Discussion
אביב קסוטואביב קסוטו 

How to extract key in sObject array using value of a field in php

i have an sObject array that has the following objects:

[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"
    }

Now, i have a string array of ids (for this example lets say it contains only "111"). What would be the best way to iterate over the object array and exatract the key of the object where id__c = "111"? in this example it would return "0".

Any help would be greatly appreciated.

Best Answer chosen by אביב קסוטו
אביב קסוטואביב קסוטו
This is a question i asked in "stack overflow" as well as in here, the asnwer you copied from the answer i got there is a bit incomplete, the correct use is "$element->fields[Id__c]", it is mentioned in the comments of the original question in "stack overflow". Thank you for the help anyway.

All Answers

NagendraNagendra (Salesforce Developers) 
Hi,

Use array_filter like this:
$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); 
Will output:

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

    )

    )
  • For the Sobject version, replace $element['fields']['Id_c'] with $element->fields['Id_c']
  • Also if you would like to pass a variable inside the callback function use:
$result = array_filter($array,
    function($element) use($externalVariable){
        return $element['fields']['Id_c'] == $externalVariable ? true :false;
});
Please mark this as solved if it's resolved so that others can benefit out of it if they are encountering a similar issue.

Best Regards,
Nagendra.

 
אביב קסוטואביב קסוטו
This is a question i asked in "stack overflow" as well as in here, the asnwer you copied from the answer i got there is a bit incomplete, the correct use is "$element->fields[Id__c]", it is mentioned in the comments of the original question in "stack overflow". Thank you for the help anyway.
This was selected as the best answer