我有两个阵列。
<?php
//Array 1
$txt_bln[] = array($bln_txt => 0);
echo json_encode($txt_bln)
//the result :[{"Januari":0},{"Februari":0},{"Maret":0},{"April":0},{"Mei":0},{"Juni":0},{"Juli":0},{"Agustus":0},{"September":0},{"Oktober":0},{"November":0},{"Desember":0}]
//Array 2
$data_bln_2[] = array($bln_txt_2 => (int)$results_jmlh['total']);
echo json_encode($data_bln_2)
//the result :[{"April":1},{"Oktober":1},{"Desember":8}]
?>
如何基于阵列2修改阵列1.结果将如下所示:
//the result :[{"Januari":0},{"Februari":0},{"Maret":0},{"April":1},{"Mei":0},{"Juni":0},{"Juli":0},{"Agustus":0},{"September":0},{"Oktober":1},{"November":0},{"Desember":8}]
然后将其更改为php数组。最终输出:
[0,0,0,1,0,0,0,0,0,1,0,8]
感谢您的帮助。
答案 0 :(得分:0)
您在寻找array_merge
吗?
http://php.net/manual/en/function.array-merge.php
array array_merge ( array $array1 [, array $... ] )
将一个或多个数组的元素合并在一起,以便将一个值的值附加到前一个数组的末尾。它返回结果数组。
如果输入数组具有相同的字符串键,则该键的后一个值将覆盖前一个键。但是,如果数组包含数字键,则后面的值不会覆盖原始值,但会附加。
带有数字键的输入数组中的值将使用从结果数组中的零开始的递增键重新编号。
如果您想忘记字符串键以获取数字键,我猜您正在寻找array_values
。
http://php.net/manual/en/function.array-values.php
array array_values ( array $array )
array_values()返回数组中的所有值,并以数字方式索引数组。
答案 1 :(得分:0)
<?php
$previous=json_decode('[{"Januari":0},{"Februari":0},{"Maret":0},{"April":0},{"Mei":0},{"Juni":0},{"Juli":0},{"Agustus":0},{"September":0},{"Oktober":0},{"November":0},{"Desember":0}]',true);
//replace json value with your variables
$current=json_decode('[{"April":1},{"Oktober":1},{"Desember":8}]',true);
//replace json value with your variable
$latest=array();
$modified_latest=array();
foreach($previous as $p)
{
$found=false;
foreach($current as $c)
{
if(key($p)==key($c))
{
$latest[]=$c;
$modified_latest[]=$c[key($c)];
$found=true;
break;
}
}
if(!$found)
{
$latest[]=$p;
$modified_latest[]=$p[key($p)];
}
}
echo json_encode($latest);
//outputs : [{"Januari":0},{"Februari":0},{"Maret":0},{"April":1},{"Mei":0},{"Juni":0},{"Juli":0},{"Agustus":0},{"September":0},{"Oktober":1},{"November":0},{"Desember":8}]
print_r($modified_latest);
//outputs :Array ( [0] => 0 [1] => 0 [2] => 0 [3] => 1 [4] => 0 [5] => 0 [6] => 0 [7] => 0 [8] => 0 [9] => 1 [10] => 0 [11] => 8 )
//that means : [0,0,0,1,0,0,0,0,0,1,0,8]