在str_replace之后更改变量的值

时间:2015-09-21 11:00:09

标签: php json

我有一个JSON值,我需要在json中提取值并将它们转换为特定格式。请参阅下面的代码

<?php

 $jsonString ='{"generelist":{"genere1":"Adventure","genere2":"Action","genere3":"Action","genere4":"Action"}}';

 $obj = json_decode($jsonString,true);
 $genere=array();

 foreach ($obj['generelist'] as $key => $value) 
    {
        //echo "<br>------" . $key . " => " . $value;
        $genere[$key] = $value;

    }

 $val3=implode(' ', $genere);
 $val3=str_replace(' ', '=1 OR ', $val3);
 print $val3;
 ?>

$val3的值显示为Adventure=1Action=1Action=1Action

现在,我想将'=1'添加到$val3的最后一个

Adventure=1Action=1Action=1Action =1

如何添加?

4 个答案:

答案 0 :(得分:1)

如果你想这样做,只需将它们连接起来。

$jsonString ='{"generelist":{"genere1":"Adventure","genere2":"Action","genere3":"Action","genere4":"Action"}}';

 $obj = json_decode($jsonString,true);
 $genere=array();

 foreach ($obj['generelist'] as $key => $value) 
    {
        //echo "<br>------" . $key . " => " . $value;
        $genere[$key] = $value;

    }

 $val3=implode(' ', $genere);
 $val3=str_replace(' ', '=1 OR ', $val3);
 $val3 .= '=1';
 print $val3;

答案 1 :(得分:0)

添加最后一行:
$val3 = $val3."=1";

答案 2 :(得分:0)

使用array_walk为每个类添加= 1的优雅变体,然后将它们全部加入implode:

 $jsonString ='{"generelist":{"genere1":"Adventure","genere2":"Action","genere3":"Action","genere4":"Action"}}';
 $obj = json_decode($jsonString,true)['generelist'];

array_walk($obj,function(&$item1, $key){$item1="$item1=1";});
$string = implode(' OR ', $obj);
print $string;

答案 3 :(得分:0)

您也可以这样做:

$jsonString ='{"generelist":{"genere1":"Adventure","genere2":"Action","genere3":"Action","genere4":"Action"}}';
$obj = json_decode($jsonString,true);
$genere=array();
foreach ($obj['generelist'] as $key => $value) 
{
    //echo "<br>------" . $key . " => " . $value;
    $genere[$key] = $value."=1";
}

$val3=implode(' ', $genere);
$val3=str_replace(' ', 'OR ', $val3);
print $val3;