为什么 php foreach 循环没有与多维 json 对象一起运行

问题描述

我没有进入 PHP foreach 循环。

$cogsAmount = '[{"name":"cogItem","amount":2},{"name":"cogItem","amount":2}]';
$multipleCogsAccount = '{"cog1":"1","cog2":"2"}';
if ($cogsAmount && count($cogsAmount) > 0) {
    foreach ($cogsAmount as $key => $cog) {
         $cogName = $cog['name'];
         if (!array_key_exists($cogName,$multipleCogsAccount)) {
              echo "The key is not exist";
              
         }
    }
}

解决方法

因为它是一个字符串!这是一个不可迭代的对象

<?php

$cogsAmount = json_decode('[{"name":"cogItem","amount":2},{"name":"cogItem","amount":2}]',1);

$multipleCogsAccount = json_decode('{"cog1":"1","cog2":"2"}',1);
if ($cogsAmount && count($cogsAmount) > 0) {
    foreach ($cogsAmount as $key => $cog) {
         echo $cogName = $cog['name'];
         //if (!array_key_exists($cogName,$multipleCogsAccount)) {
         //     echo "The key is not exist";
              
         //}
    }
}
,

这有效,如果你 json_decode() 那些字符串

$cogsAmount = json_decode('[{"name":"cogItem1",{"name":"cogItem2",true);
$multipleCogsAccount = json_decode('{"cog1":"1",true);
if ($cogsAmount && count($cogsAmount) > 0) {
    foreach ($cogsAmount as $key => $cog) {
         
         if (!array_key_exists($cog['name'],$multipleCogsAccount)) {
              echo "The key $cog[name] does not exist\n";
              
         }
    }
}

结果


The key cogItem1 does not exist
The key cogItem2 does not exist