用另一个数组php替换/更改数组值


Replace/Change array value with another array php

我有两个数组。

<?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]

谢谢你的帮助。

<?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]

你在找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()返回数组中的所有值,并对数组进行数字索引。