简体   繁体   English

添加到二级多维数组php

[英]adding to a secondary multi dimensional array php

I am retrieving data from a database. 我正在从数据库中检索数据。 The final results i am looking for is a multidimensional array with the key being an integer and the value being another array. 我正在寻找的最终结果是一个多维数组,键是整数,值是另一个数组。

The data being held is questions and answer to help my study for an exam, (NOT on PHP!) 所保存的数据是问题和答案,可以帮助我进行考试学习(不支持PHP!)

I would like the data to be like below: 我希望数据如下所示:

100 = {question,answer}
101 = {question,answer}
102 = {question,answer}
103 = {question,answer}
etc . . . 

I then will be able to call any question/answer i want. 然后,我将可以拨打我想要的任何问题/答案。

My problem lies below, 我的问题在下面,

The line 线

$tempArray[$row['question']] = $row['answer'];

works as expected, i have my question and answer 按预期工作,我有我的问题和答案

but, the line 但是,线

$this->categoryArray[$count] = $tempArray;

does not, $count is never used as expected, when i check it with 不会,当我检查$ count时,它从未按预期使用

print_r(array_keys($this->categoryArray)

i get 0,1,2 - instead of 100,101,102 我得到0,1,2-而不是100,101,102

As always Mr Internet, your help is always appreciated. 与Internet先生一如既往,您的帮助总是值得赞赏的。

Full code below 完整代码如下

$count = 100;
while($row = $stmt ->fetch())
{
   $tempArray[$row['question']] = $row['answer'];
   $this->categoryArray[$count] = $tempArray;
   $count++;
   unset($tempArray);
}

Is this close to what you are looking for? 这与您想要的东西接近吗?

$count = 100;


$qa = array(
    "question1" => "answer1",
    "question2" => "answer2",
    "question3" => "answer3"
    );

$category_array = array();

foreach($qa as $question=>$answer) {
    $category_array[$count] = array($question=>$answer);
    $count++;
}

print_r($category_array);

outputs: 输出:

Array
(
    [100] => Array
        (
            [question1] => answer1
        )

    [101] => Array
        (
            [question2] => answer2
        )

    [102] => Array
        (
            [question3] => answer3
        )

)

As I can see you are using it inside the class, I am right? 如我所见,您正在课堂上使用它,对吗? Is $count inside the function or out of? 是$ count在函数内还是在函数外?

If yes, please also use $this->count instead of $count... 如果是,请也使用$ this-> count代替$ count ...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM