PHP ARRAY附带“\”

时间:2015-12-15 12:17:35

标签: php mysql arrays json web-services

我试图从数据库中获取一些Hashtags并通过json编码发送到ios应用程序。

但不幸的是我在数组

中得到了一些“\”
    {
    "error_code": 0,
    "response_string": "success.",
    "result":    "#manchesterunited\",\"#manunited\",\"#mufc\",\"#manchesterisred\",\"#manunitedisred\",\"#middleast"
}

但我需要以下值

{
    "error_code": 0,
    "response_string": "success.",
    "result": {
        "#manchesterunited",
        "#manunited",
        "#mufc",
        "#manchesterisred",
        "#manunitedisred",
        "#middleast"
    }
}

我的PHP代码

$handle = fopen('php://input','r');
$jsonInput = fgets($handle);
$params = json_decode($jsonInput,true);

$searchword = isset($params['hash'])?$params['hash']:'';


$sql = mysql_query("SELECT `hashtags` FROM `video`");

//Fetching the sql data

$hashtags = Array();
while ($row = mysql_fetch_array($sql)) {
    $hashtags[] =  $row['hashtags'];  
}

$hashtags = array_unique($hashtags);
$string = rtrim(implode($hashtags));


$string = explode(",", $string);
$string = array_unique($string);

// Search the array with "preg_match" function.
$matches = array();
foreach($string as $k=>$v) {
   if(preg_match("/^$searchword/", $v)) {
    unset($matches[$k]);
        $matches[$k] = $v;
   }
}

$output = array_slice($matches, 0, 10, true);
$value = implode(",", $output);


echo json_encode(array("error_code"=>0,'response_string'=>'success.','result' =>$output));
exit;

这是我用来从db和fetch获取数据的PHP代码。

1 个答案:

答案 0 :(得分:0)

您可以使用带有条带的str_replace();stripslashes();

$output = stripslashes(array_slice($matches, 0, 10, true));
$value = implode(",", $output);

或分两个阶段

$output = array_slice($matches, 0, 10, true);
$output = stripslashes($output);
$value = implode(",", $output);

str_replace()

$output = array_slice($matches, 0, 10, true);
$output = str_replace('\', '', $output);
$value = implode(",", $output);