json - PHP Str_replace is not working in foreach loop -
here code.
i trying inspect link steam item. have tried use preg_replace no luck either.
$api_link = sprintf("http://steamcommunity.com/id/*steamid*/inventory/json/730/2?trading=1"); $json = file_get_contents($api_link); $json_output = json_decode($json); $result = $json_output; $link = array(); $id = array(); foreach($result->rgdescriptions $item){ $empty = array(); $newstring = $item->actions[0]->link; if($newstring == null){ continue; } else { $empty['link'] = $newstring; array_push($link, $empty); } } foreach($result->rginventory $inventory){ $empty = array(); if($inventory->instanceid == 0){ continue; } else { $empty['id'] = $inventory->id; array_push($id, $empty); } } $array = array_merge($id, $link); foreach($array $final){ $assetid = "%assetid%"; echo str_replace($assetid, $final['id'], $final['link']); }
}
but not working. please see if can help.
as can see have array of arrays:
// bracket squares equivalent of array() keyword php >=v5.4 // here // $link = array(['link'=>'url'],['link'=>'url']) // $id = array(['id'=>'id'],['id'=>'id']) // result be: // array(['link']=>'url'],['link'=>'url'],['id'=>'id'],['id'=>'id']) $array = array_merge($id, $link); foreach($array $final){ // here first $final // array('link'=>'url') $assetid = "%assetid%"; // here try // 'id' , 'link' echo str_replace($assetid, $final['id'], $final['link']); }
i think it's kind of mistake.
ok, test script:
<?php $a = array( array('link'=>'hello1'), array('link'=>'hello2')); $b = array( array('id'=>'id0'), array('id'=>'id1')); $c = array_merge($a, $b); var_dump($c);
result:
array(4) { [0] => array(1) { 'link' => string(6) "hello1" } [1] => array(1) { 'link' => string(6) "hello2" } [2] => array(1) { 'id' => string(3) "id0" } [3] => array(1) { 'id' => string(3) "id1" } }
array_merge doesn't mix associative arrays between them nether nor particular item (i hope explain correct)
of course
foreach ($c $item) { var_dump($item); }
will enumerate items 1 one
array(1) { 'link' => string(6) "hello1" } array(1) { 'link' => string(6) "hello2" } array(1) { 'id' => string(3) "id0" } array(1) { 'id' => string(3) "id1" }
and there no array has both of them (link
, id
) in item
this script can't associate link
, id
properly, cause of links can skipped continue
, of id
can skipped. , random list of available information. can stuck in next situation:
- $links has first 10 links - $id has 3,4,5,7,9,11
it's list. if have only pure info (no other details), can't associate between of them using shown source.
here minimum 1 simple solutions:
don't skip, don't merge, add empty array, , final loop this:
$assetid = "%assetid%"; ($link $key=>$final) { if (count($final) && count($id[$key])) { echo str_replace($assetid, $id[$key]['id'], $final['link']); } else { // of needed arguments absent } }
Comments
Post a Comment