I’d like to do a loop with these JSON strings.
$json_m = '[
{"name":"1","value":"1"},
{"name":"2","value":"2"},
{"name":"3","value":"3"},
{"name":"4","value":"4"},
{"name":"5","value":"5"},
]';
$json_a = '[
{"name":"1-m","value":"1"},
{"name":"2-m","value":"3"},
{"name":"3-m","value":"5"},
]';
I do a loop and on $json_m
. If the value exists in both JSON, I set the parameter to TRUE
This is my current code:
$jm = json_decode($json_m, true);
$ja = json_decode($json_a, true);
$i = 0;
$is_exist = FALSE;
foreach($jm as $rows ){
if($rows["value"] == $ja[$i]["value"]){
$is_exist = TRUE;
}
$dataadd = array ( 'ID' => $i,
'NAME' => $rows["value"],
'STATUS' => $is_exist
);
$i++;
}
This script returns as all FALSE, based on my example the STATUS
should return like this:
TRUE
FALSE
TRUE
FALSE
TRUE
Do I miss something or what? Any help is greatly appreciated.
2
Answers
You could make your life easier by extracting all the
value
values from$ja
usingarray_column
; you can then search that usingin_array
. You can then iterate$jm
usingarray_map
to produce an array of$dataadd
values:Output (for your sample data):
You can do using array_search like below