需要一些帮助,不断地来回寻找可能的方法。我正在FileMaker中创建一个基本的调查屏幕,并使用PHP来获取我的结果。我需要以可用的格式整理调查数据,以便我可以绘制数据图表。当我使用PHP查询FileMaker时,它返回一个相当大的数据数组。使用下面的代码,我设法输出以下内容:
foreach ($data as $key => $question)
{
echo $question->getField('Question').' - '. $question->getField('Answer').'<br />';
}
我的输出
Has the noise around the surrounding are increased with the new store opening – Strongly Agree
Has the noise around the surrounding are increased with the new store opening – Strongly Agree
Has the noise around the surrounding are increased with the new store opening – Agree
Has the noise around the surrounding are increased with the new store opening – Disagree
Has the noise around the surrounding are increased with the new store opening – Strongly Disagree
Do you think the store closing earlier at weekend would help with noise levels - Strongly Disagree
Do you think the store closing earlier at weekend would help with noise levels - Strongly Disagree
Do you think the store closing earlier at weekend would help with noise levels - Strongly Agree
Do you think the store closing earlier at weekend would help with noise levels - Strongly Disagree
Do you think the store closing earlier at weekend would help with noise levels – Disagree
我现在需要整理这些数据,无论是数组格式还是json格式。我正在尝试使用下面的格式,因为它看起来最简单。
[Question][StronglyAgree][Agree][Disagree][StronglyDisagree]
[Has the noise around the surrounding are increased with the new store opening][2][1][1][2]
[Do you think the store closing earlier at weekend would help with noise levels][1][0][1][3]
Etc….
我在FileMaker脚本中执行此操作的方法是循环使用$ data数组,将当前指针上的问题与最后一个问题(最后一个指针)进行比较。如果它的不同把问题的值放在问题数组变量中。这将获得我所有的独特问题。看看php文档,我发现array_unique可以为我做所有这些但是我不能让它与我的foreach一起使用($ data as $ key =&gt; $ question)。
一旦我得到了我独特的问题,我就会循环通过$ data数据与我正在搜索的所有强烈同意的问题进行比较,然后将此值放入第一个[]的问题中。我再次为每个问题循环3次同意,不同意......
是否有人知道教程或答案,这将有助于我将这些结果与问题的答案数量结合起来。对格式不太感兴趣,如下所示会起作用
Has the noise around the surrounding are increased with the new store opening,2,1,1,2
Or
{“Question":"John", “Strongly Agree”:2,“Agree”:1,“Disagree”:1,“Strongly Disagree”:2 },
作为最后的手段,我正在考虑为每个问题查询数据库4次,但这将是太多的调用和杀死性能。将返回的值转换为以某种方式格式化的变量。听起来有点过分,但可能我最终会采用的方法比循环更容易理解。
答案 0 :(得分:1)
为什么不将问题用作数组键?
/*
* @var array $surveyResults: [
* "My Question" => [
* "Question" => "My Question" ,
* "Strongly Agree" => 2,
* ... etc ...
* ]
* ]
*/
$surveyResults = [];
foreach ($data as $key => $question) {
// if we have not processed this question before, add it to the survey results
if (!isset($surveyResults[$question->getField('Question')])) {
$surveyResults[$question->getField('Question')] = [
"Question" => $question->getField('Question'),
"Strongly Agree" => 0,
"Agree" => 0,
"Disagree" => 0,
"Strongly Disagree" => 0
];
}
// count answer
$surveyResults[$question->getField('Question')][$question->getField('Answer')]++:
}
echo json_encode($surveyResults);
这应该像你建议的那样给出结果。