除了爆炸之外,在PHP中拆分一个值

时间:2014-02-14 09:42:09

标签: php

我如何以城市,街道和建筑的形式分割这个价值?除了explode函数。

value = { city: "Indore", street: "dd102, 302-raj palace, Indrapuri", building: "dd" }

这不是json,这是正常的ajax。

我如何将此转换为Json?这是我的javascript看起来像:

$('#address').editable({
            url: redirecturl,
            value: {
                city: "<?php echo $EditUserDetails->city; ?>",
                street: "<?php echo $EditUserDetails->address; ?>"

            },
            validate: function (value) {
                if (value.city == '') return 'city is required!';
            },
            display: function (value) {
                if (!value) {
                    $(this).empty();
                    return;
                }
                var html = '<b>' + $('<div>').text(value.city).html() + '</b>, ' + $('<div>').text(value.street).html() + ', ' + $('<div>').text(value.building).html();
                $(this).html(html);
            }
        });

3 个答案:

答案 0 :(得分:0)

$value = '{ city: "Indore", street: "dd102, 302-raj palace, Indrapuri", building: "dd" }';

$value = trim(str_replace("\",", "\";", $value), "{}");
$array = explode(";", $value);
$object = array();

foreach ($array as $item)
{
    $temp = explode(": ", str_replace('"', '', trim($item)));
    $object[$temp[0]] = $temp[1];
}

print_r($object);

输出:

Array ( 
    [city] => Indore 
    [street] => dd102, 302-raj palace, Indrapuri 
    [building] => dd 
) 

答案 1 :(得分:0)

编辑:更正了代码。 如果结果以这种格式提供:

$value = 'value = { city: "Indore", street: "dd102, 302-raj palace, Indrapuri", building: "dd" }';

您可以使用:

$value = 'value = { city: "Indore", street: "dd102, 302-raj palace, Indrapuri", building: "dd" }';
$value = preg_replace('/(\w+):/', '"$1":', $value);
$value = preg_replace('/.*({.*\}).*/', '$1', $value);
$object = json_decode($value);

echo '<pre>';
print_r($object);
echo '</pre>';

答案 2 :(得分:0)

在你的ajax请求中添加:

  

类型: “JSON”

之后你可以使用json_decode();