数组搜索键和替换值php

时间:2018-09-09 13:43:25

标签: php arrays

我有一个像这样的数组

[{"detail":"33,putih","sku":"123","price":"500000","stok":"8"},{"detail":"33,hitam","sku":"123","price":"500000","stok":"5"},{"detail":"43,hitam","sku":"123","price":"1000000","stok":"1"}]

我必须对其进行json_decode。

我想从详细信息“ 33,hitam”更改stok = 2。

但是我很困惑首先使用数组搜索并使用数组替换。

2 个答案:

答案 0 :(得分:0)

您可以这样:

$stringarray = '[{"detail":"33,putih","sku":"123","price":"500000","stok":"8"},{"detail":"33,hitam","sku":"123","price":"500000","stok":"5"},{"detail":"43,hitam","sku":"123","price":"1000000","stok":"1"}]';
$array = json_decode($stringarray);
var_dump($array);
$replaced = replaceInObject($array, "detail", "33,hitam", "stok" , "2");
var_dump($replaced);

function replaceInObject($array, $field, $searchvalue, $valuefield, $newvalue){
    foreach($array as $element){
        if($element->$field == $searchvalue){
            $element->$valuefield = $newvalue;
        }
    }
    return $array;
}

答案 1 :(得分:0)

您可以使用array_map实现这一目标

$data = '[{"detail":"33,putih","sku":"123","price":"500000","stok":"8"},{"detail":"33,hitam","sku":"123","price":"500000","stok":"5"},{"detail":"43,hitam","sku":"123","price":"1000000","stok":"1"}]';
$json = json_decode($data, true);

$result = array_map(function($e) {
                        if ($e['detail'] == "33,hitam") $e['stok'] = "2";
                        return $e;
                    }, $json);