php - Change my array dynamically -
i have function returns array this:
[ "var0 => 300 pr. d. joÃo", "var1 =>a passar", "var2 =>", "var3 => 904 q.bela vista", "var4 =>a passar", "var5 =>", "var6 => 905 monte virgem", "var7 =>a passar", "var8 =>", "var9 => 300 telheira - c", "var10 =>a passar", "var11 =>", "var12 => 200 cast. queijo", "var13 =>20:39", "var14 =>5min" ]
and need result next example: it's necessary in format.
[ "route" => "300 pr. d. joÃo", "eta" =>"a passar", "waittime" =>"", "route" => "904 q.bela vista", "eta" =>"a passar", "waittime" =>"", "route" =>" 905 monte virgem", "eta" =>"a passar", "waittime" =>"", "route" =>" 300 telheira - c", "eta" =>"a passar", "waittime" =>"", "route" =>" 200 cast. queijo", "eta" =>"20:39", "waittime" =>"5min" ]
and webservice php code is:
function getpage ($codigo) { $link = "http://www.stcp.pt/pt//itinerarium/soapclient.php?codigo="; $dom = new domdocument(); $homepage = file_get_contents($link.$codigo); $dom->loadhtml($homepage); $tables = $dom->getelementsbytagname('table'); $table = $tables->item(0); $i = 0; $var = array(); foreach ($table->childnodes $tr) { if ($tr->nodename == 'tr') { foreach ($tr->childnodes $td) { $i++; $tds= $td->nodevalue; if ($i%2 == 0) { } else { array_push($var, $tds); } } } else { echo "string "; } } $first = array_shift($var); $second = array_shift($var); $third = array_shift($var); $maxvar = sizeof($var); $final_array = array(); ($k=0; $k < sizeof($var); $k++) { ${'var' . $k} = $var[$k]; array_push($final_array, "var$k =>".$var[$k]); } echo json_encode($final_array); }
how can return json example show?
because associative arrays must have unique keys, cannot have route
, eta
, or waittime
appearing more once in output. can create nested array represents data quite nicely.
$a = [ "var0 => 300 pr. d. joÃo", "var1 =>a passar", "var2 =>", "var3 => 904 q.bela vista", "var4 =>a passar", "var5 =>", "var6 => 905 monte virgem", "var7 =>a passar", "var8 =>", "var9 => 300 telheira - c", "var10 =>a passar", "var11 =>", "var12 => 200 cast. queijo", "var13 =>20:39", "var14 =>5min" ]; function removevarprefix($x) { return preg_replace('/^var\d+\s*=>\s*/', '', $x); } $b = array_map(function($set) { list($route, $eta, $waittime) = array_map('removevarprefix', $set); return ['route'=>$route, 'eta'=>$eta, 'waittime'=>$waittime]; }, array_chunk($a, 3)); echo json_encode($b, json_pretty_print);
output (updated show json)
[ { "route": "300 pr. d. jo\u00c3o", "eta": "a passar", "waittime": "" }, { "route": "904 q.bela vista", "eta": "a passar", "waittime": "" }, { "route": "905 monte virgem", "eta": "a passar", "waittime": "" }, { "route": "300 telheira - c", "eta": "a passar", "waittime": "" }, { "route": "200 cast. queijo", "eta": "20:39", "waittime": "5min" } ]