【问题标题】:array_push not working for integers?array_push 不适用于整数?
【发布时间】:2017-04-23 13:00:55
【问题描述】:

我正在使用array_push 方法将所有整数放入数组中,如下所示。

$response = json_decode($jsonResponse);
 foreach($response as $item) { //foreach element in $response
     $type = $item; 
     $unique_id = $type->id;
     $id_array=array();
     array_push($id_array, $unique_id);     
 }  
 var_dump($id_array);

但是$id_array 只包含最后一个整数元素。上面的代码有什么问题或者我们不能将整数元素推入php数组吗?

【问题讨论】:

  • 您正在通过在循环中初始化数组来重置数组。把它排除在循环之外
  • @Rishi 哦,不。明白了。谢谢

标签: php arrays array-push


【解决方案1】:

$id_array=array();放在foreach的开头

$response = json_decode($jsonResponse);
  $id_array=array();
  foreach($response as $item) { //foreach element in $response
      $type = $item; 
      $unique_id = $type->id;
      array_push($id_array, $unique_id);     
  }  
 var_dump($id_array);

你可以在foreach中最小化代码

$response = json_decode($jsonResponse);
$id_array=array();
foreach($response as $item) { //foreach element in $response
    $unique_id = $item->id;
    array_push($id_array, $unique_id);     
}  
var_dump($id_array);

$response = json_decode($jsonResponse);
$id_array=array();
foreach($response as $item) { //foreach element in $response
  array_push($id_array, $item->id);     
}  
var_dump($id_array);

【讨论】:

  • 或者只是array_push($id_array, $item->id);
【解决方案2】:

在循环外初始化数组:

$response = json_decode($jsonResponse);
$id_array = array();
foreach($response as $item) { //foreach element in $response
    $type = $item; 
    $unique_id = $type->id;
    array_push($id_array, $unique_id);     
}  

【讨论】:

    【解决方案3】:
    $response = json_decode($jsonResponse);
    $id_array=array();
    foreach($response as $item) { //foreach element in $response
       $type = $item; 
       $unique_id = $type->id;
       array_push($id_array, $unique_id);     
    }  
    var_dump($id_array);
    

    这应该可行..

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-09-18
      • 2012-01-07
      • 2014-04-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多