如何向多维数组添加新的关联数组键?

时间:2016-03-14 22:56:07

标签: php mysql session multidimensional-array foreach

我正在尝试将一个名为“name”的新值添加到名为“company_ *”的关联数组中,这是作为MySQL查询结果存储在“result”关联数组中的五家公司之一。

我怀疑将每个公司设置为foreach中的局部变量不会更新$ result的内部数组值,但我找不到解决方案。下面是我用来执行任务的代码:

$member_id = $_SESSION['member_id']; // The member_id of who is logged in
  if ($stmt = $mysqli->query("SELECT * FROM member_answers WHERE member_id = '$member_id'")) {

    if ($stmt->num_rows == 5) {
      $result = $stmt->fetch_all(MYSQLI_ASSOC);

      // Let's also set up company names by querying for the company name in the DB
      foreach ($result as $company) {
        $tempID = $company['company_id'];
        $query = $mysqli->query("SELECT name FROM companies WHERE company_id = `$tempID` LIMIT 1");
        $name = mysqli_fetch_row($query);
        $company['name'] = $name[0];
      }

      // Set up the session variables
      $_SESSION['company_one'] = $result[0];
      $_SESSION['company_two'] = $result[1];
      $_SESSION['company_three'] = $result[2];
      $_SESSION['company_four'] = $result[3];
      $_SESSION['company_five'] = $result[4];
      $_SESSION['all_companies'] = $result;
      $_SESSION['chosen_companies'];

0 个答案:

没有答案