将会话值附加到API请求php的现有数组结构
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了将会话值附加到API请求php的现有数组结构相关的知识,希望对你有一定的参考价值。
我正在使用API,其中每个API请求都应该重新发送所有以前的值。我将所有以前的值存储在php会话中。结果数组结构是json_encoded并用于Curl请求。除了向现有问题添加新问题外,一切工作正常。以下是代码:
$question_counter = ++$_SESSION['question_counter'];
$questionidnew = strip_tags($_POST['questionid1']);
$answernew = strip_tags($_POST['answer1']);
//store new questions as session array
$_SESSION['questions'][$question_counter] = array(
'questionid' => $questionidnew,
'questionanswer' => $answernew,
);
$question_array[] = $_SESSION['questions'];//previous questions
print_r($question_array);
给出以下结果:
Array ( [0] => Array (
[1] => Array ( [questionid] => p_48 [questionanswer] => absent )
[2] => Array ( [questionid] => p_122 [questionanswer] => absent )
) )
如何将其以格式附加到现有数据结构:
$to_json = [
'sex' => $gender,
'age' => $age,
'evidence' => [
['id' => $test_id1, 'choice_id' => 'present', 'initial' => true],
['id' => $test_id2, 'choice_id' => 'present', 'initial' => true],
['id' => $questionidnew, 'choice_id' => $answernew],
['id' => 'p_12', 'choice_id' => $choice, 'initial' => true],
['id' => $location, 'choice_id' => 'present', 'initial' => true]
],
'extras' => [
'disable_users' => true
],
];
由于我是一名新手程序员,我收到错误并发现有点令人困惑的是为会议的先前问题添加以下内容:
['id' => $questionidnew, 'choice_id' => $answernew],
请求帮助。
答案
如果我正确读取此内容,您想要将所有新答案添加到$ to_json数组中,对吧?我最终做了以下工作来实现这一目标。我采取了自由,可能会被误解,所以如果这没有用,请纠正我:
<?php
session_start();
if(!isset($_SESSION['question_counter'])) {
$_SESSION['question_counter'] = 0;
}
$gender = "male";
$age = 46;
$test_id1 = 12;
$test_id2 = 24;
$questionidnew = 9;
$answernew = "B";
$choice = "A";
$location = "campus";
$to_json = array(
'sex' => $gender,
'age' => $age,
'evidence' => array(
array('id' => $test_id1, 'choice_id' => 'present', 'initial' => true),
array('id' => $test_id2, 'choice_id' => 'present', 'initial' => true),
array('id' => $questionidnew, 'choice_id' => $answernew),
array('id' => 'p_12', 'choice_id' => $choice, 'initial' => true),
array('id' => $location, 'choice_id' => 'present', 'initial' => true)
),
'extras' => array(
'disable_users' => true
),
);
$question_counter = ++$_SESSION['question_counter'];
//$questionidnew = strip_tags($_POST['questionid1']);
//$answernew = strip_tags($_POST['answer1']);
//store new questions as session array
$_SESSION['questions'][$question_counter] = array(
'questionid' => $questionidnew,
'questionanswer' => $answernew,
);
$question_array[] = $_SESSION['questions'];//previous questions
echo "<pre>";
print_r($to_json);
echo "</pre>";
//$_SESSION['names'][] = $name;
foreach($question_array as $question) {
foreach($question as $key => $value) {
$to_json['evidence'][] = array('id' => $value['questionid'], 'choice_id' => $value['questionanswer']);
}
}
echo "<pre>";
print_r($to_json);
echo "</pre>";
print_r(json_encode($to_json));
?>
以上是关于将会话值附加到API请求php的现有数组结构的主要内容,如果未能解决你的问题,请参考以下文章