我有一些json数据,我想在匹配某些条件后重新安装它。
$mm='a';
$nn='104';
$jn=array();
$j2='[
{"a":"c","n":"103","t":"rfg"},
{"a":"a","n":"104","t":"bmf"},// <- find the data, re-install from the next line
{"a":"b","n":"105","t":"tit"},
{"a":"a","n":"106","t":"iou"},
{"a":"b","n":"107","t":"wdf"}
]';
$t2=json_decode($j2);
foreach($t2 as $d2){
if($mm==$d2->a&&$nn==$d2->n){
continue;
}
$jn['a']=$d2->a;
$jn['n']=$d2->n;
$jn['t']=$d2->t;
$p.=json_encode($jn).',';
}
echo '['.substr($p,0,-1).']';
我需要将json数据作为[{"a":"b","n":"105","t":"tit"},{"a":"a","n":"106","t":"iou"},{"a":"b","n":"107","t":"wdf"}]
答案 0 :(得分:0)
我希望你能理解。
<?php
$mm='a';
$nn='104';
$jn=array();
$j2='[
{"a":"c","n":"103","t":"rfg"},
{"a":"a","n":"104","t":"bmf"},// <- find the data, re-install from the next line
{"a":"b","n":"105","t":"tit"},
{"a":"a","n":"106","t":"iou"},
{"a":"b","n":"107","t":"wdf"}
]';
$t2=json_decode($j2);
$i=0;
foreach($t2 as $d2)
{
if($mm==$d2->a && $nn==$d2->n)
{
$jn['a']=$d2->a;
$jn['n']=$d2->n;
$jn['t']=$d2->t;
if($i==1)
{
$p=json_encode($jn).',';
}
else
{
$p.=json_encode($jn).',';
}
}
$i++;
}
echo '['.substr($p,0,-1).']';
答案 1 :(得分:-1)
以下代码将完成这项工作 仅在找到匹配项后附加字符串。
$mm='a';
$nn='104';
$jn=array();
$j2='[{"a":"c","n":"103","t":"rfg"},{"a":"a","n":"104","t":"bmf"},{"a":"b","n":"105","t":"tit"},{"a":"a","n":"106","t":"iou"},{"a":"b","n":"107","t":"wdf"}]';
$t2=json_decode($j2);
//echo "<pre>";
//print_r($t2);
//exit();
$append = false;
$p='';
foreach($t2 as $key=>$d2){
$jn['a']=$d2->a;
$jn['n']=$d2->n;
$jn['t']=$d2->t;
if($append){
$p.=json_encode($jn).',';
}
if($mm==$d2->a&&$nn==$d2->n){
$append=true;
}
}
echo '['.substr($p,0,-1).']';