douxiu6835 2016-11-20 05:36
浏览 79

使用foreach循环填充数组?

I'm trying to populate the array for the variable $example_data. I have an array of Mass' and dates that I want to populate this array with. However I do not know how to create a new array entry for each $mass[$x] and $date[$x] that I want to store. I've tried putting a foreach loop inside the $example_data = array( but it didnt work.

This is what I want it to do, but doesn't work:

$example_data = array(
    foreach($exer->results() as $ex){
        $mass = $ex->Mass;
        $date = $ex->Date;

        array($date,$mass),
);

This is what I've tried but not sure how to complete it:

$userID = $user->data()->id;

$sql = "SELECT * FROM userdetails WHERE UserID = ".$userID."";
$details = DB::getinstance()->query($sql);

$x = 1;

foreach($details->results() as $detail){
    /** getting data from each record from field Mass and storing it in $mass array **/
    $mass[$x] = $detail->Mass;
    $date[$x] = $detail->Date;

    $x++;
}

$x = 1;

$example_data = array(
        array($date[$x],$mass[$x]),
        /** I want it to create a new array entry for each $mass[] **/
);
  • 写回答

1条回答 默认 最新

  • dongpao1921 2016-11-20 05:56
    关注

    It depends on the type of database you're using...

    For example if you're using MySQL, it's mysqli_fetch_assoc()

    You're trying to fetch a result set into an associative array but the result set itself is an associative array

    try...

    $sql = "SELECT * FROM userdetails WHERE UserID = ".$userID."";
    $details = DB::getinstance()->query($sql);
    
    $example_data = array(
      array("Mass"),
      array("Date")
    );
    
    
    while($row = $details->fetch_assoc()) {
        array_push($example_data['Mass'], $row['name_of_mass_column_in_db']);
        array_push($example_data['Date'], $row['name_of_date_column_in_db']);
      }
    }
    

    Basically, you can just fetch an associative array instead of populating an associative array with an associative array...

    评论

报告相同问题?

悬赏问题

  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line