从多维数组和循环访问数据

时间:2015-07-16 13:39:46

标签: php arrays loops

我正在努力从嵌套数组中提取数据。

以下是我的代码:

$active_tsquery = db_select("SELECT * FROM timesheets WHERE     status=\"cand\" OR status=\"client\" ORDER BY weekending ASC"); 
var_dump($active_tsquery);

foreach($active_tsquery as $key => $value) {
    $candid[] = $active_tsquery[$key]["candid"];
    $clientid[] = $active_tsquery[$key]["clientid"];
}

db_select函数供参考:

function db_select($query) {
    $rows = array();
    $result = db_query($query);

    // If query failed, return `false`
    if($result === false) {
        return false;
    }

    // If query was successful, retrieve all the rows into an array
    while ($row = mysqli_fetch_assoc($result)) {
        $rows[] = $row;
    }
    return $rows;
}

db_query函数供参考:

function db_query($query) {
    // Connect to the database
    $connection = db_connect();

    // Query the database
    $result = mysqli_query($connection,$query);

    return $result;
}

var_dump很好 - 从数据库返回所有内容。

array (size=15)
  0 => 
    array (size=29)
  'ts_id' => string '5453' (length=4)
  'clientid' => string '503' (length=3)
  'candid' => string '714' (length=3)
  'weekending' =>
  'department' =>
  'orderno' =>
  'monhrs' =>
  'tueshrs' =>
  'wedshrs' =>
  'thurshrs' =>)
  'frihrs' =>
  'sathrs' =>
  'sunhrs' =>
  'totalhrs' =>
  'basichrs' =>
  'othrs' =>
  'ot2hrs' =>
  'basicpay' =>
  'basiccharge' =>
  'otpay' =>
  'otcharge' =>
  'ot2pay' =>
  'ot2charge' =>
  'authname' =>
  'authdate' =>
  'ip' =>
  'status' =>
  'hue' =>
  'huc' =>

我尝试做的是在$ candid中循环遍历每个来自$ active_tsquery(其中15个)的id,运行下面的查询并将结果存储在一个数组中供以后使用。我应该在第一个中使用另一个foreach循环吗?

"SELECT * FROM timesheetlogin WHERE id="

感谢您的任何建议

1 个答案:

答案 0 :(得分:1)

使用以下方法对其进行排序:

$active_tsquery = db_select("SELECT * FROM timesheets WHERE status=\"cand\" OR status=\"client\" ORDER BY weekending ASC"); 
    //var_dump($active_tsquery);

    foreach($active_tsquery as $key => $value) {
        $clientid = $value["clientid"];
        $weekend = $value["weekending"];
        $clientresult = db_select("SELECT * FROM timesheetlogin WHERE id=\"$clientid\"");
        $candid = $value["candid"];
        $candresult = db_select("SELECT * FROM timesheetlogin WHERE id=\"$candid\"");

        foreach ($clientresult as $key => $value) {
            $company = $value["company"];
        }
        foreach ($candresult as $key => $value) {
            $candidate = $value["name"];
        }
    }