简体   繁体   中英

PHP: how to generate this JSON?

I have an array `$a', includes the following data:

[0]=>'text',
[1]=>'text1, text2, text3'

I want to generate a JSON object from this data, as follow:

'{"TestingApplications": [
    { "ApplicationName": "text" },
    { "ApplicationName": "text1" },
    { "ApplicationName": "text2" },
    { "ApplicationName": "text3" }
  ]
}'

What I did:

<?php

$a=array(0=>"text", 1=>"text1, text2, text3");

$r = array();

foreach($a as $key => $val){

    if (strpos($val,',') !== false) {

        $v = explode(',', $val);

        foreach($v as $k => $l){

            array_push($r, $l);
        }
    } else{

        array_push($r, $val);
    }
}

So, how I can generate the required JSON using the data stored in $r ?

I'd start by creating the basic structure of the json object:

$temp = [
    'TestingApplications' => [],
];

Next, iterate over the data you have, and explode all of the comma-containing strings like you're doing right now:

foreach ($a as $value) {
    $exploded = explode(',', $value);//no need to check for comma's
    foreach ($exploded as $name) {
        //perhaps consider calling trim on $name here
        $temp['TestingApplications'][] = ['ApplicationName' => $name];
    }
}

Then finally, json_encode the lot:

return json_encode($temp);

Although truth be told: I'd really try to change the way the data is provided to my code. If all the string values should be treated the same way, it's totally unacceptable that sometimes, they're assigned to a distinct key (in the $a array), but that on other occasions, they're in a comma separated string.
This, to me at least, looks like an XY problem

Try as below :

<?php
$a=array(0=>"text", 1=>"text1, text2, text3");

$r = array();$final = array();

foreach($a as $key => $val){

    if (strpos($val,',') >= 0) {

        $v = explode(',', $val);

        foreach($v as $k => $l){

            $r[]['ApplicationName']= "$l";
        }
    }
}
$final['TestingApplications'] = $r;

echo json_encode($final);
?>

You can try json_encode . This will returns the JSON representation of a value

For example:

$arr = array(0=>"text", 1=>"text1, text2, text3");
echo json_encode($arr);

Hope this help you well.

json_encode(); is used to convert data in json from array in php.

$array = array('TestingApplications'=>array( "appname1"=>"text1","appname2"=>"text2", "appname3"=>"text3"));
echo json_encode($array);

Assuming you have this source:

$sourceArray = array(
    'text',
    'text1, text2, text3',
);

You need to build the right PHP array before you convert it to JSON. I propose to do so in a recursive way, while trimming the empty spaces too:

// get a flat array
$tmpArray = array_map(function($array) {
    return explode(',', $array);
}, $sourceArray);

$flatArray = array();
array_walk_recursive($tmpArray, function($a) use (&$flatArray) {
    $flatArray[] = trim($a);
});

$toJsonArray = array('TestingApplications' => array());
foreach ($flatArray as $val) {
    $toJsonArray['TestingApplications'][] = array(
        'ApplicationName' => $val,
    );
}

Then you just have to encode it to JSON: echo json_encode($toJsonArray);

To generate required JSON Object, array should be like following:

$arr = array(
'TestingApplications' => array(
    array('ApplicationName' => 'text'),
    array('ApplicationName' => 'text1'),
    array('ApplicationName' => 'text2'),
    array('ApplicationName' => 'text3'),
)

);

and then encode this array to json as: echo json_encode($arr); It will return required JSON Object

try this.

$a=array(0=>"text", 1=>"text1,text2,text3");

$r = array();


    foreach($a as $key => $val){

        if (strpos($val,',') !== false) {

            $v = explode(',', $val);

            foreach($v as $k => $l){
                $final['ApplicationName']=$l;
                $final_arr[]=$final;
            }
        } else{
                $final['ApplicationName']=$val;
                $final_arr[]=$final;
        }
    }


    $result['TestingApplications']=$final_arr;
    echo json_encode($result);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM