注意:未定义的偏移量:0 foreach

时间:2018-06-29 15:19:19

标签: php for-loop

我正在尝试通过API获取响应并将其存储在数据库中

'Get End of Month of Previous Month - Pass today's date
EOM = GetEOMPrev(Date.Today)

'Get First of Month of Previous Month - Pass date just calculated
FOM = GetFOMPrev(EOM)

这给出了错误

  

注意:未定义的偏移量:0在C:\ xampp \ htdocs \ api \ index.php中   33警告:为中的foreach()提供了无效的参数   第33行的C:\ xampp \ htdocs \ api \ index.php

我得到的API响应是

print_r($result_arr);
//is printing all the data and my next line is 
foreach ($result_arr[0]["http_response_body"]["Items"] as $key => $value) {

3 个答案:

答案 0 :(得分:0)

您将获得具有三个嵌套级别的多维数组的API响应。

正确的访问方式是

foreach($result_arr as $key=>$val)
{
   print_r($val); // this line for reference prints [0] array elements
   foreach($val as $key1=>$val1)
   {
        echo $val1['SKU']; // prints 123
   }
}

答案 1 :(得分:0)

这就是你得到的:

print_r($result_arr);

这给你这个数组:

Array ( 
    [Items] => 
        Array ( 
            [0] => Array ( 
                [SKU] => 123 
                [Quantity] => 13 
                [ProductName] => tet prod 
                [Description] => blah blah ... 

这就是你要做的:

foreach ($result_arr[0]["http_response_body"]["Items"] as $key => $value) {

得到Notice: Undefined offset: 0只是因为您可以看到数组中没有$result_arr[0]

所以就做:

foreach ($result_arr["Items"] as $key => $value) {

它应该可以工作!

希望有帮助

答案 2 :(得分:0)

似乎您的数组是这样构建的:

$result_arr["Items"][] = array( "sku"=>123, "qty" => 44, "ProductName" => "tet prod", "Description" => "blahh" );

您可以像下面这样遍历此数组:

foreach ($result_arr["Items"] as $key => $value) {
    echo "key: " . $key . ", sku:" . $value["sku"] . ", prod:" . $value[ "ProductName" ] . "<br />";
}

foreach ($result_arr["Items"] as $items ) {
    foreach( $items as $key => $value ) {
        echo $key . "/" . $value . "<br />";
    }
}