【问题标题】:Foreach - determine if key exists in each iterationForeach - 确定每次迭代中是否存在键
【发布时间】:2021-05-27 09:27:50
【问题描述】:

我有以下数组。

我试图弄清楚如何在 foreach 中创建一个 if 语句,该语句将根据任何单个索引是否具有 [Customer_Facing_Comments__r] 来设置真或假

我正在使用此代码 - 但是,这只是告诉我 [Customer_Facing_Comments__r] 是否在数组中 - 每次都在。我需要查看它是否在每个索引 [0]、[1]..etc 中...并在此基础上设置 true 或 false。

代码:

    foreach($queryResult->records as $record){
    if (array_key_exists("Customer_Facing_Comments__r",$record)) {
    $test = 'true'; }
    else { $test = 'false'; } }

QueryResult Object
(
    [queryLocator] => 
    [done] => 1
    [records] => Array
        (
            [0] => stdClass Object
                (
                    [Id] => 5003xx0255mhcAAA
                    [Account] => stdClass Object
                        (
                            [Id] => 0010cxx026IwsTAAS
                            [Name] => xxx
                        )
                    [AccountId] => 0010c0xxwsTAAS
                    [Customer_Facing_Comments__r] => stdClass Object
                        (
                            [done] => 1
                            [queryLocator] => 
                            [records] => Array
                                (
                                    [0] => stdClass Object
                                        (
                                            [Id] => 
                                            [Comment__c] => test string
                                            [CreatedDate] => 2021-02-13T00:25:50.000Z
                                            [Trouble_Ticket__c] => 5003x0000255mhcAAA
                                        )
                                )
                            [size] => 1
                        )
                    [Type] => Service Down
                )
            [1] => stdClass Object
                (
                    [Id] => 5003x000024Y6TpAAK
                    [Account] => stdClass Object
                        (
                            [Id] => 0010c0cccc6IwsTAAS
                            [Name] => test
                        )
                    [AccountId] => 0010c00cccIwsTAAS
                )

【问题讨论】:

  • 你想要什么结果?主数组中每个元素的真假数组?
  • (删除了之前的评论 - 看来array_key_exists() 会将对象转换为数组并在 stdClass 上毫无怨言地工作。
  • 是的 AbraCadaver
  • $test = 'false' 好像不太对
  • 请始终通过复制粘贴var_export() 的输出来展示您的数组/对象数据结构,以便志愿者可以立即在他们的演示中使用您的示例数据。

标签: php salesforce-lightning


【解决方案1】:

只需公开foreach 中的密钥并在结果数组$test 中使用它:

foreach($queryResult->records as $key => $record){
    if (isset($record->Customer_Facing_Comments__r)) {
        $test[$key] = 'true';
    } else {
        $test[$key] = 'false';
    }
}

【讨论】:

    猜你喜欢
    • 2013-11-20
    • 1970-01-01
    • 2018-11-29
    • 2015-01-22
    • 1970-01-01
    • 2022-01-20
    • 2021-12-17
    • 2021-10-05
    相关资源
    最近更新 更多