2017-10-18 46 views
0

我請求PHP文件闡述一些的AjaxPOSTdata無法在一個PHP foreach循環迭代陣列

POST數據

data[0][id]:359 
data[0][position]:1 
data[1][id]:321 
data[1][position]:2 
data[2][id]:354 
data[2][position]:3 

Request.php

if(isset($_POST['data'])) { 
    if(isset($_SESSION['username']) && isset($_SESSION['password'])) { 

     $verify = $loggedIn->verify(); 

     if($verify['username']) { 
      $Profile = new Profile(); 
      $Profile->db = $db; 
      //Call my function 
      $messages = $Profile->setOrder($_POST['data']);  

     } 
    } 
} 

Profile.php

function setOrder($post) { 
    var_dump($post); 

    foreach($post as $item) 
    { 
     return "Area ID ".$item["id"]." and person located ".$item["position"]."<br />"; 
    } 
} 

我的函數沒有返回值和$post轉儲是如下

array(3) { 
    [0]=> 
    array(2) { 
    ["id"]=> 
    string(3) "359" 
    ["position"]=> 
    string(1) "1" 
    } 
    [1]=> 
    array(2) { 
    ["id"]=> 
    string(3) "321" 
    ["position"]=> 
    string(1) "2" 
    } 
    [2]=> 
    array(2) { 
    ["id"]=> 
    string(3) "354" 
    ["position"]=> 
    string(1) "3" 
    } 
} 

在我的功能,我可以dump正確像var_dump($post[0]["id"]);爲什麼我foreach環路空?

+0

嘗試'var_dump($ item);'循環內部。也許它會揭示一些東西。 –

+2

你實際上並沒有告訴你的foreach()輸出任何東西,僅僅是'return' - 它會將該字符串賦值給'$ messages = $ Profile-> setOrder($ _ POST ['data']);'並終止循環。 – CD001

+2

你不循環,因爲'return'打破循環 –

回答

2

這是因爲您正在使用return內部循環。它會在第一次迭代後終止循環。你需要做這樣的事情。

$return = null; 
foreach($data as $item) 
{ 
    $return .= "Area ID ".$item["id"]." and person located ".$item["position"]."<br />"; 
} 
return $return;