需要帮助php到json数组

时间:2015-01-07 15:33:52

标签: php mysql arrays

我在

下面有一个字符串
$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

NEW UPDATE:

我想修改相同的字符串

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

json输出:

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

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

5 个答案:

答案 0 :(得分:2)

这应该有效,尽管可能有更好的方法。

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

答案 1 :(得分:2)

您可以在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]]}]

答案 2 :(得分:1)

试用此代码:

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

<强>输出:

  

{&#34;名称&#34;:&#34;网站&#34;&#34;数据&#34;:[&#34; OT&#34;&#34; OM&#34 ;, &#34;我们&#34;&#34; FF&#34;]}

     

{&#34;名称&#34;:&#34;网站&#34;&#34;数据&#34;:[4,6,34,45]}

问候。

答案 3 :(得分:1)

试试这个代码段:

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

答案 4 :(得分:1)

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

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