在我的PHP文件中,我总共收到了4个变量$ data,$ date,$ shift和$ val1。 $ data是一个数组,另外3个是通过AJAX获得的日期和2个字符串没有问题。我要做的是在$ data变量中插入这3个值。
我尝试使用数组合并,并为每个循环多个实例但到目前为止没有运气。
我获得了这样的变量:
if (isset($_POST['date'])){
$date = $_POST['date'];
$date = json_encode($date);
$date = json_decode($date);
}
if (isset($_POST['shift'])){
$shift = $_POST['shift'];
$shift = json_encode($shift);
$shift = json_decode($shift);
}
if (isset($_POST['val1'])){
$val1 = $_POST['val1'];
$val1 = json_encode($val1);
$val1 = json_decode($val1);
}
if (isset($_POST['data'])){
$dat = $_POST['data'];
$data = json_decode($dat, true);
}
$values = array($date,$shift,$val1);
$r = (array_merge($data, $values));
我的数据数组看起来像这样:
Array (
[0] => Array (
[data] => Array (
[0] => Array (
[0] => 1
[1] => 2
[2] => 3
[3] => 0
[4] => Mat1
[5] => Box1
[6] => 100
[7] => 100
[8] => Piece1
[9] => Loc1
[10] => Mach1
[11] => 1000
[12] => Accepted
)
)
)
[1] => 2019-04-09
[2] => First
[3] => Value1
)
但我想要实现的是:
Array (
[0] => Array (
[data] => Array (
[0] => Array (
[0] => 1
[1] => 2
[2] => 3
[3] => 0
[4] => Mat1
[5] => Box1
[6] => 100
[7] => 100
[8] => Piece 1
[9] => Suc1
[10] => Mach1
[11] => 1000
[12] => Accepted
[13] => 2019-04-09
[14] => First
[15] => Value1
)
)
)
)
我究竟做错了什么?或者我如何实现我想要做的事情?
编辑:因为我可以在我的数组中获得多个数组,就像这样
Array (
[0] => Array (
[data] => Array (
[0] => Array (...)
[1] => Array (...)
[2] => Array (...)
[3] => Array (...)
)
)
)
我刚刚将这段代码添加到@HelgeB答案中,我将它留在这里以防将来有人可能需要它。
$count = count($data[0]['data']);
for ($i=0; $i < $count ; $i++) {
$data[0]['data'][$i][] = $date;
$data[0]['data'][$i][] = $shift;
$data[0]['data'][$i][] = $val1;
}
据我所知,你的合并输出,你的$data
数组结构是$data[0]['data'][0] = [1,2,3,...,'Accepted']
。因此,在我看来,您需要在$data[0]['data'][0]
级别上准确插入值以获得结果。
实现这一目标的最简单方法是:
$data[0]['data'][0][] = $date;
$data[0]['data'][0][] = $shift;
$data[0]['data'][0][] = $val1;
如果要使用合并方法,则需要合并到正确的级别,如下所示:
$r = [0 => ['data' => [0 => (array_merge($data[0]['data'][0], $values))]]];