2017-08-01 32 views
0

我有这个PHP代码100%工作,它显示下面的结果,但是我怎样才能使用这些数据作为单独的项目?PHP/CURL/JSON:将项目分配到变量

我已经习惯了使用喜欢的事物:

$title = $data['selection3']['name']; 
echo $title 

但是,这并不在这里工作。我希望能够分离每个项目并为其分配一个变体,以便我可以用它制作一个广告。

PHP卷曲代码:

<?php 
    function origin($projecttoken,$apikey,$format) { 
     $ch = curl_init(); 
     $apiuri = 'https://www.parsehub.com/api/v2/projects/'.$projecttoken.'/last_ready_run/data?api_key='.$apikey.'&format='.$format.''; 
     curl_setopt($ch, CURLOPT_URL, $apiuri); 
     curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); 
     curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); 
     curl_setopt($ch,CURLOPT_ENCODING, ''); 
      if(curl_exec($ch) === false){ 
       echo curl_error($ch) . '<br />'; 
      } 
     $data = curl_exec($ch); 
     curl_close($ch); 
     return($data); 
    } 
?> 

    <pre> 
    <?php 
    print_r(origin('xxxxxx','xxxxxx','json')); 
    ?> 
    </pre> 

的结果:

{ 
"selection3": [ 
    { 
    "name": "Medal of Honor™ Pacific Assault", 
    "url": "https://www.origin.com/usa/en-us/store/medal-of-honor/medal-of-honor-pacific-assault/standard-edition" 
    }, 
    { 
    "name": "Join the Fight for Freedom" 
    }, 
    { 
    "name": "This World War II shooter is On the House and yours to own totally free." 
    }, 
    { 
    "name": "FREE" 
    }, 
    { 
    "name": "Get It Now", 
    "url": "" 
    } 
], 
"selection6": [ 
    { 
    "name": "Battlefield 4™ Dragon's Teeth", 
    "url": "https://www.origin.com/usa/en-us/store/battlefield/battlefield-4/expansion/battlefield-4-dragons-teeth" 
    }, 
    { 
    "name": "Upgrade Your Fight" 
    }, 
    { 
    "name": "Add this expansion to your library for free and dominate the battlefield. It's On the House! (Requires base game to play.)" 
    }, 
    { 
    "name": "FREE" 
    }, 
    { 
    "name": "Get It Now", 
    "url": "" 
    } 
] 
} 

回答

1

这一结果是在JSON。使用函数json_decode()将字符串解码为数组。你可以定期访问它的值。

例子:

$data = json_decode($result, true); 
echo $data["selection3"]["name"]; 

...其中$result代表您未知的结果字符串。

0

您使用循环这样的个人数据:

<?php 
    $data = origin('xxxxxx','xxxxxx','json'); 
    $dataArray = json_decode($data, true); 
    if(!empty($dataArray){ 
    foreach($dataArray as $key => $val){ 
     $item = $dataArray[$key]; 
     echo "<pre>". json_decode($item); 
     //$item['name'], $item['url'] 
    } 
    } 
?>