1

I am having a string below

$string = ot>4>om>6>we>34>ff>45

I would like the JSON output be like

 [{"name":"website","data":["ot","om","we","ff"]}]

and

 [{"name":"websitedata","data":["4","6","34","45"]}]

what I've tried

$query = mysql_query("SELECT month, wordpress, codeigniter, highcharts FROM project_requests");
$category = array();
$category['name'] = 'website';

$series1 = array();
$series1['name'] = 'websitedata';

while($r = mysql_fetch_array($query)) {
    $category['data'][] = $r['month'];
  }
$result = array();
array_push($result,$category);
array_push($result,$series1);

print json_encode($result, JSON_NUMERIC_CHECK);

but the above code is applicable only if the data are present in rows from a mysql table, what i want is achieve the same result with the data from the above string. that is

  $string = ot>4>om>6>we>34>ff>45

NEW UPDATE:

I would like to modify the same string

$string = ot>4>om>6>we>34>ff>45

into

json output:

[
     {
          "type" : "pie",
          "name" : "website",
          "data" : [
               [
                    "ot",
                     4
               ],
               [  
                    "om",
                    6
               ],
               [  
                    "we",
                    34
               ]
           ]
     }
]

I have updated the answer please check the json part, I would like the php code. regards

4
  • You should use some sort of regular expression or string manipulation to convert string to json Commented Jan 7, 2015 at 15:39
  • Please update your question with an extra section about the extra details for 'pie charts'. So that we know exactly what is required. Commented Jan 7, 2015 at 18:16
  • @Ryan Vincent added the edits please check now sir. Commented Jan 7, 2015 at 18:29
  • I tested my answer and it work now with the graph script. Could you please test it for yourself and see if it works for you? Commented Jan 7, 2015 at 19:10

5 Answers 5

2

You can explode() on the >s, and then loop through the elements:

$string = "ot>4>om>6>we>34>ff>45";

$array1 = [
    'name'=>'website',
    'data'=>[]
]
$array2 = [
    'name'=>'websitedata',
    'data'=>[]
]
foreach(explode('>', $string) as $index => $value){
    if($index & 1) //index is odd
        $array2['data'][] = $value;
    else //index is even
        $array1['data'][] = $value;
}

echo json_encode($array1); //prints {"name":"website","data":["ot","om","we","ff"]}
echo json_encode($array2); //prints {"name":"websitedata","data":["4","6","34","45"]}

A solution using preg_match_all():

$string = "ot>4>om>6>we>34>ff>45";

preg_match_all('/(\w+)>(\d+)/', $string, $matches);

$array1 = [
    'name'=>'website',
    'data'=> $matches[1]
];
$array2 = [
    'name'=>'websitedata',
    'data'=> $matches[2]
];

echo json_encode($array1); //prints {"name":"website","data":["ot","om","we","ff"]}
echo json_encode($array2); //prints {"name":"websitedata","data":["4","6","34","45"]}

Update:

To get the second type of array you wanted, use this:

//since json_encode() wraps property names in double quotes (which prevents the chart script from working), you'll have to build the json object manually
$string = "ot>4>om>6>we>34>ff>45";

preg_match_all('/(\w+)>(\d+)/', $string, $matches);

$data = [];
foreach($matches[1] as $index => $value){
    if(isset($matches[2][$index]))
        $data[] = '["' . $value . '",' . $matches[2][$index] . ']';
}

$type = 'pie';
$name = 'website';

echo $jsonString = '[{type:"' . $type . '",name:"' . $name . '",data:[' . implode(',', $data) . ']}]'; // prints [{type:"pie",name:"website",data:[["ot",4],["om",6],["we",34],["ff",45]]}]

Update #2:

This code uses explode(), and although it's probably not the most efficient way of doing it, it works.

//since json_encode() wraps property names in double quotes (which prevents the chart script from working), you'll have to build the json object manually
$string = "ot>4>om>6>we>34>ff>45";

$keys = [];
$values = [];

foreach(explode('>', $string) as $key => $value){
    if(!($key & 1)) //returns true if the key is even, false if odd
        $keys[] = $value;
    else
        $values[] = $value;
}

$data = [];
foreach($keys as $index => $value){
    if(isset($values[$index]))
        $data[] = '["' . $value . '",' . $values[$index] . ']';
}

$type = 'pie';
$name = 'website';

echo $jsonString = '[{type:"' . $type . '",name:"' . $name . '",data:[' . implode(',', $data) . ']}]'; // prints [{type:"pie",name:"website",data:[["ot",4],["om",6],["we",34],["ff",45]]}]
Sign up to request clarification or add additional context in comments.

6 Comments

I thought that 'property names' (strings) in JSON were required to have double quotes (")? These are treated 'correctly' in 'javascript' whether you use them 'quoted' or not? A string is a sequence of zero or more Unicode characters, wrapped in double quotes - www.json.org...
@RyanVincent I thought so too, but the graphs script he uses the object for doesn't work (for me at least) when they are wrapped in double quotes
Thanks for the quick response. more investigation needed - It is not really that complex a 'standard' to follow... sigh... ;-/
@Jonan hello sir! sir, is it possible to give this same answer without using preg_match_all ? like simply using arrays
@vigneshs I updated my answer, it now makes use of explode()
|
2

This should work, though there are probably better ways to do it.

$string = "ot>4>om>6>we>34>ff>45";

$website = ["name" => "website", "data" => []];
$websiteData = ["name" => "websitedata", "data" => []];

foreach(explode(">", $string) as $i => $s) {
    if($i % 2 === 0) {
        $website["data"][] = $s;
    } else {
        $websiteData["data"][] = $s;
    }
}

echo json_encode($website);
echo json_encode($websiteData);

A regex alternative:

preg_match_all("/([a-z]+)>(\d+)/", $string, $matches);

$website = ["name" => "website", "data" => $matches[1]];
$websiteData = ["name" => "websitedata", "data" => $matches[2]];

Comments

1

Try this code:

$string = 'ot>4>om>6>we>34>ff>45';
$string_split = explode('>', $string);

$data = array("name" => "website");
$data2 = $data;

foreach ($string_split as $key => $value)
{
    if (((int)$key % 2) === 0)
    {
        $data["data"][] = $value;
    }
    else
    {
        $data2["data"][] = $value;
    }
}

$json1 = json_encode($data, JSON_NUMERIC_CHECK);
$json2 = json_encode($data2, JSON_NUMERIC_CHECK);

echo $json1;
echo $json2;

Output:

{"name":"website","data":["ot","om","we","ff"]}

{"name":"website","data":[4,6,34,45]}

Regards.

1 Comment

sir this one worked, is it possible to produce {name:'website',type:'pie',"data":[['ot',4],['om',6]['we',34],['ff',45]]} I need it in series format highcharts.com/demo/pie-basic see that link for implementing the json to be used for pie chart thanks!
1

Try this snippet:

$strings = explode('>', 'ot>4>om>6>we>34>ff>45');
// print_r($string);

$x = 0;
$string['name'] = 'website';
$numbers['name'] = 'websitedata';

foreach ($strings as $s)
{
    if ($x == 0) {
        $string['data'][] = $s;
        $x = 1;
    } else {
        $numbers['data'][] = $s;
        $x = 0;
    }
}


print_r(json_encode($string));
echo "<br/>";
print_r(json_encode($numbers));

Comments

1

As usual - it is long winded but shows all the steps to get to the required output.

<?php //https://stackoverflow.com/questions/27822896/need-help-php-to-json-array

// only concerned about ease of understnding not code size or efficiency.

// will speed it up later...

$inString = "ot>4>om>6>we>34>ff>45";

$outLitRequired =  '[{"name":"website","data":["ot","om","we","ff"]}]';
$outValueRequired = '[{"name":"websitedata","data":["4","6","34","45"]}]';

// first: get a key / value array...
$itemList = explode('>', $inString);

/* debug */ var_dump(__FILE__.__LINE__, $itemList);

// outputs ------------------------------------
$outLit = array();
$outValue = array();

// ok we need to process them in pairs - i like iterators...
reset($itemList); // redundant but is explicit

// build both output 'data' lists
while (current($itemList)) {
    $outLit[] = current($itemList);
    next($itemList); // advance the iterator.

    $outValue[] = current($itemList);
    next($itemList);
}

/* debug */ var_dump(__FILE__.__LINE__, $itemList, $outLit, $outValue);

// make the arrays look like the output we want...
// we need to enclose them as arrays to get the exact formatting required

// i do that in the 'json_encode' statements.

$outLit = array('name' => 'website', 'data' => $outLit);
$outValue = array('name' => 'websitedata', 'data' => $outValue);

// convert to JSON.
$outLitJson = json_encode(array($outLit));
$outValueJson = json_encode(array($outValue));

// show  required and calculated values...

/* debug */ var_dump(__FILE__.__LINE__, 'OutLit', $outLitRequired, $outLitJson);
/* debug */ var_dump(__FILE__.__LINE__, 'OutValue', $outValueRequired, $outValueJson);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.