需要帮助 php 到 json 数组


Need help php to json array

>我在下面有一个字符串

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

我希望 JSON 输出是这样的

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

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

我尝试过什么

$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);

但是上面的代码仅适用于 MySQL 表中的数据存在于行中,我想要的是使用上述字符串中的数据获得相同的结果。

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

新更新:

我想修改相同的字符串

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

JSON 输出:

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

我已经更新了答案,请检查json部分,我想要php代码。问候

您可以在> s上explode(),然后遍历元素:

$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"]}

使用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"]}

更新:

要获取所需的第二种类型的数组,请使用以下命令:

//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]]}]

更新#2:

此代码使用 explode() ,虽然它可能不是最有效的方法,但它是有效的。

//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]]}]

这应该有效,尽管可能有更好的方法可以做到这一点。

$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);

正则表达式替代方案:

preg_match_all("/([a-z]+)>('d+)/", $string, $matches);
$website = ["name" => "website", "data" => $matches[1]];
$websiteData = ["name" => "websitedata", "data" => $matches[2]];

试试这段代码:

$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;

输出:

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

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

问候。

试试这个片段:

$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));

像往常一样 - 它冗长,但显示了获得所需输出的所有步骤。

<?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);