簡體   English   中英

需要幫助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代碼。 問候

盡管應該有更好的方法可以執行此操作。

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

您可以在> 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';
$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;

輸出:

{“名稱”:“網站”,“數據”:[“ ot”,“ om”,“我們”,“ ff”]}

{“名稱”:“網站”,“數據”:[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);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM