使数组脱离循环

时间:2019-02-27 13:03:44

标签: php loops

我需要使数组脱离循环(我需要使用数组,而不是最后一个值)

循环

for ($x = 1; $x < $numero; $x++) {
$frase = $frase_script[$x];
$distrito1 = (explode(',',$frase));

echo $distrito1[0]}

可变出

$ultimo_nome = $distrito1[0];

我需要使用数组,而不是最后一个值

echo "<br> I need print array, and not, last value".$ultimo_nome;

错误:打印最后一个值而不是数组。

Example

所有代码

 $ch = curl_init(); 

curl_setopt($ch, CURLOPT_URL, "http://api.geonames.org/searchJSON?username=country=pt&lang=pt&q=lisbon&fcode=ADM2&adminCode1=14&style=SHORT&maxRows=1000");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_HEADER, FALSE);

curl_setopt($ch, CURLOPT_HTTPHEADER, array(
  "Accept: application/json"
));

$response = curl_exec($ch);
curl_close($ch);
$frase_script = (explode(',',$response));

$frase = $frase_script[0];
$palavra = (explode(':',$frase));
$numero = $palavra[1];    

$frase_script = (explode('"name":',$response));

echo '[';

for ($x = 1; $x < $numero; $x++) {
    $frase = $frase_script[$x];
    $distrito1 = (explode(',',$frase));

    echo $distrito1[0]; }


$ultimo_nome = $distrito1[0];

echo $ultimo_nome;


echo ']';

echo "<br> I need print array, and not, last value".$ultimo_nome;

1 个答案:

答案 0 :(得分:0)

如果您需要打印所有元素,但不需要打印出来,则可以使用

$distrito1 = (explode(',',$frase));
$numElem = count($distrito1); 

foreach ($distrito1 as $key => $value){
  if ( $key < $numElem-1 ){
     echo $value;
  } else {
   break;
  }
}