如何在 php 中格式化数组

我有这段代码:


$id = 1;

$isTemplate = true;

$address = "address, \n tel. 1234455";

我需要以这种形式保存它:


{"results": [{

            "id": 1,

            "isTemplate": true,

            "text": "<span class=\"d-block option-head\">\n    nazwa\n</span>\n<span class=\"d-none\"> - </span>\n<span class=\"d-block option-sub\">\n        address,\n                tel. 123456\n    </span>"

        ]}

我怎样才能做到?


我尝试:


$resultArray = array('results' => ['id'=> 1, 'isTemplate' => true, 'text'=> '<span class="d-block option-head">\n    nazwa\n</span>\n<span class="d-none"> - </span>\n<span class="d-block option-sub">\n        address,\n                tel. 1234455\n    </span>']);

但我的结果是错误的:


Array

(

    [results] => Array

        (

            [id] => 1

            [isTemplate] => 1

            [text] => <span class="d-block option-head">\n    nazwa\n</span>\n<span class="d-none"> - </span>\n<span class="d-block option-sub">\n        address,\n                tel. 123455\n    </span>

        )


)

请帮我


哆啦的时光机
浏览 174回答 4
4回答

慕容森

$id = 1;$isTemplate = true;$address = "address, \n tel. 1234455";$array = [&nbsp; &nbsp; 'results' => [&nbsp; &nbsp; &nbsp; &nbsp; [&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; 'id' => $id,&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; 'isTemplate' => $isTemplate,&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; 'text' => $address,&nbsp; &nbsp; &nbsp; &nbsp; ],&nbsp; &nbsp; ],];$result = json_encode($array);

蝴蝶不菲

尝试这个您只需要再添加 1 个嵌套。$resultArray = ['results' => [['id'=> 1, 'isTemplate' => true, 'text'=> '<span class="d-block option-head">\n&nbsp; &nbsp; nazwa\n</span>\n<span class="d-none"> - </span>\n<span class="d-block option-sub">\n&nbsp; &nbsp; &nbsp; &nbsp; address,\n&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; tel. 1234455\n&nbsp; &nbsp; </span>']]];echo '<pre>';print_r(json_encode($resultArray));exit;

慕少森

您的代码缺少嵌套级别。$resultArray = array('results' => [&nbsp; &nbsp; ['id' => 1, 'isTemplate' => true, 'text' => '<span class="d-block option-head">\n&nbsp; &nbsp; nazwa\n</span>\n<span class="d-none"> - </span>\n<span class="d-block option-sub">\n&nbsp; &nbsp; &nbsp; &nbsp; address,\n&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; tel. 1234455\n&nbsp; &nbsp; </span>']]);var_dump($resultArray, json_encode($resultArray));

慕桂英4014372

&nbsp;$id = 1;&nbsp; &nbsp; &nbsp; &nbsp; $isTemplate = true;&nbsp; &nbsp; &nbsp; &nbsp; $address = "address, \n tel. 1234455";&nbsp; &nbsp; &nbsp; &nbsp; $text= '<span class="d-block option-head">\n&nbsp; &nbsp; nazwa\n</span>\n<span class="d-none"> - </span>\n<span class="d-block option-sub">\n&nbsp; &nbsp; &nbsp; &nbsp; address,\n';&nbsp; &nbsp; &nbsp; &nbsp; $array[] = ['id'=>$id ,'isTemplate'=>$isTemplate, 'address' => $address,'text'=>$text];&nbsp; &nbsp; &nbsp; &nbsp; $value = json_encode($array);$value 将保存所需的结果......
打开App,查看更多内容
随时随地看视频慕课网APP