对每个元素运行php action


Run php action for every element

我有一个php脚本,从mysql数据库检索数据。一切都很好,但我的问题是,这个$result = $dao->joinedEvents($userId);返回一组数字,我想做的是为每个ID运行这个$secondResult = $dao->joinedEventsInfo($receivedIds);,我现在使用的这个脚本只返回一个ID的数据。

这是我的php脚本的一部分:
$userId = htmlentities($_REQUEST["userId"]);
$result = $dao->joinedEvents($userId); //This is getting the IDs array
if(!empty($result)) {

$receivedIds = $result["event_id"];
$ids = explode(",", $receivedIds);
foreach($ids as $id){
    $secondResult = $dao->joinedEventsInfo($id);
    if(!empty($secondResult)) {   
        $returnValue["finalResult"][] = $secondResult;    
    } else {    
        $returnValue["status"] = "error";   
        $returnValue["message"][] = "Could not find records for id" . $id;
    }
}

} else {
    $returnValue["status"] = "Empty error"; 
    $returnValue["message"] = "Could not find records";
}

$dao->closeConnection();
echo json_encode($returnValue);

这是joinedEvents脚本:

public function joinedEvents($userId){
     $returnValue = array();
    $sql = "SELECT event_id from MyTable WHERE userId= '$userId' LIMIT 0 , 30";
      $statement = $this->conn->prepare($sql);
        if (!$statement)
            throw new Exception($statement->error);
        $statement->execute();
        $result = $statement->get_result();
         while ($myrow = $result->fetch_assoc()) 
         {
           $returnValue[] = $myrow;
         }
         return $returnValue;
    }

这是joinedEventsInfo脚本:

public function joinedEventsInfo($eventId){
     $returnValue = array();
     $sql = "SELECT * FROM Events WHERE eventId = '$eventId' LIMIT 0 , 30";
    $statement = $this->conn->prepare($sql);
    if (!$statement)
        throw new Exception($statement->error);
    $statement->execute();
    $result = $statement->get_result();
     while ($myrow = $result->fetch_assoc()) 
     {
       $returnValue[] = $myrow;
     }
     return $returnValue;
 }

Edit:我需要这个的原因是我有两个表。第一个中只有id,第二个中有info。因此,首先我需要获取ID,然后我需要获取刚刚收到的每个ID的数据。

非常感谢,我完全卡住了。

根据更新后的代码片段和下面的讨论,可以发现$result确实是一个数组,并且解决方案为:

$userId = htmlentities($_REQUEST["userId"]);
$result = $dao->joinedEvents($userId);
if(count($result)){
    foreach($result as $array){
        $event_id = $array['event_id'];
        $secondResult = $dao->joinedEventsInfo($event_id);
        if(!empty($secondResult)) {  
            $returnValue["finalResult"][] = $secondResult;    
        } else {    
            $returnValue["status"] = "error";  
            $returnValue["message"][] = "Could not find records for id: " . $event_id;
        }
    }
}else {
    $returnValue["status"] = "Empty error";
    $returnValue["message"] = "Could not find records";
}
$dao->closeConnection();
echo json_encode($returnValue);

您尝试过array_map()吗?这将允许您轻松地对数组的每个成员调用php函数。

另一种方法是使用常见的while ($row = mysql_fetch_array($result)),它将对返回结果的每一行执行while循环中的代码。注意,您可能必须将mysql_fetch_array更改为SQL连接的特定值。