如何将foreach放入数组

我有这个

// tell the user
 $homedata = $user->getbanks();

    foreach ($homedata as $data)

echo json_encode(array("replies" => array(


                           array("message" =>      $data->bankname),



            )));

} 如何将其放入数组中。我尝试了它,只给了我最初的内容。请帮忙。

评论
  • Out
    Out 回复

    If you are creating an array with only banknames then you can do like this:

    $stmt = $db->prepare("select *  from banknames");
                $stmt->execute();
                $data = $stmt->fetchAll(PDO::FETCH_OBJ);
                return $data;
    $names = [];
    foreach($data as $replies){
        $names[] = $replies["bankname"];
    }
    
    print_r($names); exit;
    

    或者,如果仅需要银行名称,则在SQL查询本身中,仅获取银行名称。 即

    $stmt = $db->prepare("select bankname from banknames");
                $stmt->execute();
                $data = $stmt->fetchAll(PDO::FETCH_OBJ);