php foreach循环在json_decode中有2个变量

时间:2015-03-07 11:07:32

标签: php json foreach

在foreach循环中,我试图与两个变量的数据建立链接。像这样:

$baseAttachementUrl = str_replace($rowAttachTags, $rowAttachVals, $getAttachmentURL);

foreach ($attachments as $attachment){ 
$rowAttachTags = array('{{ROWID}}', '{{SHEETID}}','{{ATTACHMENTID}}');
$rowAttachVals = array($addRowsObj->result[0]->id, $theSheet->id, $attachment->id);
$getAttachmentURL = $baseAttachementUrl; 
$getNEWAttachmentURL = str_replace($rowAttachTags, $rowAttachVals, $getAttachmentURL);

$curlSession = curl_init($getNEWAttachmentURL);
curl_setopt($curlSession, CURLOPT_HTTPHEADER, $header);
curl_setopt($curlSession, CURLOPT_RETURNTRANSFER, TRUE);
getAttachmentResponse = curl_exec($curlSession);

$getFileObj = array(json_decode($getAttachmentResponse, true));

foreach ($getFileObj as $fileObj){
echo "<a href='". $fileObj['url']."'>". $fileObj['name']."</br></a>";       
}
}

表格中的第一行有效。 2个文件带有正确的URL。但是在所有后续行中,第一行中的最后一个文件出来了。

2 个答案:

答案 0 :(得分:0)

这里有几个问题,你不是太具体了。但是我会尽力回应。

首先,我们不知道$attachments$getFileObj的结果如何。我们假设您的问题部分“返回stdClas ...”是$getFileObj结果的一部分。

另一个问题是我们不知道你从哪里得到$getAttachmentURL ..这是一个静态设置的变量,还是$attachments导致的变量?

考虑到这些问题我相信你要做的就是首先获取所有附件并将它们存储到$attachments中。然后,您希望从您的初始结果中获取每个附件URL并遍历每个以获取您的fileURL。我会做以下事情:

<?php

curl_setopt($curlSession, CURLOPT_HTTPHEADER, $header);
curl_setopt($curlSession, CURLOPT_RETURNTRANSFER, TRUE);
$getAttachmentsResponse = curl_exec($curlSession);
// Assign response to variable
$attachments = json_decode($getAttachmentsResponse);


foreach ($attachments as $attachment) {
    $getAttachmentURL = $attachment->attachment_URL;
    $curlSession = curl_init($getAttachmentURL);
    curl_setopt($curlSession, CURLOPT_HTTPHEADER, $header);
    curl_setopt($curlSession, CURLOPT_RETURNTRANSFER, TRUE);
    $getAttachmentResponse = curl_exec($curlSession);
    // Assign response to variable 
    $getFileObj = json_decode($getAttachmentResponse);
    echo "<td>";
    echo "<a href='" . $getFileObj->url . "'>" . $attachment->name . "</br></a>";
    echo "</td>";
}

答案 1 :(得分:0)

...试

// ... curl setup
$attach = json_decode($getAttachmentsResponse);
// ... curl setup two
$file = json_decode($getAttachmentResponse);
$joinedattachment[ 'attach' ] = $attachone;
$joinedattachment[ 'file' ]   = $file;
$attachments[] = $joinedattachment;

$iCountAttachments = count( $attachments );
echo "<td>";      
for( $i = 0; $i < $iCountAttachments; ++$i )
{
    echo "<a href='". $attachments[ $i ][ 'file' ]."'>". $attachments[ $i ][ 'attach' ] ."</br></a>";
}
echo "</td>"; 
相关问题