【问题标题】:foreach loop stops after first iterationforeach 循环在第一次迭代后停止
【发布时间】:2023-03-11 08:46:03
【问题描述】:

尝试从 xml 文件中提取 id,将其传递给 api 查询,然后将结果加载到 dom 文档中。事情是我的foreach 循环只返回第一次迭代,然后似乎停止了。

为什么不回去获取下一个PROGRAM_ID

//load results of first api call into simplexml - print_r here gives me a big array with all the expected rows in it
$progsitecontent = simplexml_load_file($progsiteapi);

//set which nodes to step through to reach required information
$totalprogsitecontent = $progsitecontent->matrix->rows->row;

//for each instance of a program id in this simplexml file:
foreach($totalprogsitecontent->PROGRAM_ID as $progid)
{

    //...substitute the program id into the api call
    $programdetails = $progdetailsapi_start.$progid.$progdetailsapi_end;
    $complete_program_details = simplexml_load_file($programdetails);

    //now for each instance of a programs info, load into a DOM document and carry out the below actions - from here down already works in another script so im sure the problem has to be above this point 

    $prog_info = $complete_program_details->matrix->rows->row;

    //create the top line container tag
    $row = $doc->createElement ("programInformation");

    //create the container tag
    $progID = $doc->createElement("programId");
    //fill it with the information you want
    $progID->appendChild ( $doc->createTextNode ( $prog_info->PROGRAM_ID ) );
    //attach this information to the row
    $row->appendChild($progID);

    //repeat for each element you want to include
    $progName = $doc->createElement("programName");
    $progName->appendChild ( $doc->createTextNode ( $prog_info->PROGRAM_NAME ) );
    $row->appendChild($progName);

    $progURLs = $doc->createElement("programUrls");
    $progURLs->appendChild ( $doc->createTextNode ( $prog_info->PROGRAM_URLS ) );
    $row->appendChild($progURLs);

    $progLogo = $doc->createElement("programLogo");
    $progLogo->appendChild ( $doc->createTextNode ( $prog_info->MERCHANT_LOGO ) );
    $row->appendChild($progLogo);

    $r->appendChild ($row);

}

echo $doc->saveXML();

请随意评论其中的任何内容是如何编写的。我还处于“一见倾心”的阶段:)

【问题讨论】:

  • $totalprogsitecontent 的结果是什么?
  • 发布 $totalprogsitecontent 的 xml 部分
  • $totalprogsitecontent->PROGRAM_ID 是一个数组吗?
  • 我稍微改变了一下,所以 $totalprogsitecontent 变成了 $progsitecontent。 $progsitecontent 的 print_r 给了我一个大数组,而不是 xml。
  • 没有按返回的意思......几分钟后返回 xml

标签: php foreach


【解决方案1】:

没有看到$totalprogsitecontent的完整结果就不能说太多,但我认为它应该是这样的:

foreach($totalprogsitecontent as $progid)
{
...
}

由于 $totalprogsitecontent->PROGRAM_ID 已经是一个值 - 所以您正在迭代这个元素而不是数组。

另外,您的 $progid 在 for 循环中是小写的,但您引用的是 $progID -- PHP 区分大小写。


查看您的 XML 代码后,它应该是这样的。

foreach($progsitecontent->matrix->rows->row as $row){
     $progid = $row['PROGRAM_ID'];
     $affid = $row['AFFILIATE_ID'];
}

【讨论】:

  • 感谢您的留言。我已将变量更改为相同的情况,但删除 ->matrix->rows->row->PROGRAM_ID 已阻止它返回甚至第一次迭代
  • 嗨,尼克,它已排序,谢谢!问题是我在 xml 中深入挖掘了一个节点。我正在寻找 matrix->rows->row->programID 下的每条数据 我真正想要的是寻找 matrix->rows->row 下的每条数据,然后从 $row 对象 Cheers