I'm Try To Access Some specific Value From Return JSON
Real Value is 79#45#597#10#10#10000#M
$retframe = str_ireplace('#',',', $stframe);
echo json_encode(array( 'Value' => $retframe));
///Output Response Back is
{"Value":"79,45,597,10,10,10000,M"}
I Want to Get Only Value of 79,597,10
If you need the 1st, 3rd and 5th number of $stframe
$stframe = '79#45#597#10#10#10000#M';
list($p1,$p2,$p3,$p4,$p5,$p6,$p7) = explode('#',$stframe);
$retframe = $p1 . ',' . $p3 . ',' . $p5;
echo json_encode(array( 'Value' => $retframe));
if you want to get 79,597,10 values statically than you will do it like this way.
$retframe = str_ireplace('#',',', $stframe);//$retframe = '79,45,597,10,10,10000,M';
$rs = explode(",",$retframe);
$array[] = $rs[0];
$array[] = $rs[2];
$array[] = $rs[3];
$array1= implode(",", $array);
echo json_encode(array( 'Value' => $array1));
and you will get result like this : {"Value":"79,597,10"}
Related
I am getting some extra slashes while making json array using PHP. My code is below.
<?php
$output=array(array("first_name"=>"robin","last_name"=>"sahoo","reg_no"=>12,"paper_code"=>"BA001","subject"=>"Mathematics"),array("first_name"=>"robin","last_name"=>"sahoo","reg_no"=>12,"paper_code"=>"BA002","subject"=>"History"),array("first_name"=>"Rama","last_name"=>"Nayidu","reg_no"=>13,"paper_code"=>"BA001","subject"=>"Geology"),array("first_name"=>"robin","last_name"=>"sahoo","reg_no"=>12,"paper_code"=>"BA003","subject"=>"Science"));
$result = []; // Initialize result array
foreach ($output as $key => $value) {
$name = $value['first_name'] . ' ' . $value['last_name'];
// check if same name already has entry, create one if not
if (!array_key_exists($name, $result)) {
$result[$name] = array(
'reg_no' => $value['reg_no'],
'name' => $name,
'paper1' => '',
'paper2' => '',
'paper3' => '',
'paper4' => ''
);
}
// count array elements with value, then set paper number and value
$paper = 'paper' . (count(array_filter($result[$name])) - 1);
$result[$name][$paper] = $value['paper_code'].'/'.$value['subject'];
}
$result = array_values($result); // reindex result array
echo json_encode($result);exit;
?>
Here the json output is given below.
[{"reg_no":12,"name":"robin sahoo","paper1":"BA001\/Mathematics","paper2":"BA002\/History","paper3":"BA003\/Science","paper4":""},{"reg_no":13,"name":"Rama Nayidu","paper1":"BA001\/Geology","paper2":"","paper3":"","paper4":""}]
Here my problem is I am adding $value['paper_code'].'/'.$value['subject']; and in output I am getting "BA001\/Mathematics". Here One extra slash(\) is added which I need to remove.
You can add JSON_UNESCAPED_SLASHES as the second parameter. LIke:
$result = array_values($result); // reindex result array
echo json_encode($result,JSON_UNESCAPED_SLASHES);exit;
This will result to:
[{"reg_no":12,"name":"robin sahoo","paper1":"BA001/Mathematics","paper2":"BA002/History","paper3":"BA003/Science","paper4":""},{"reg_no":13,"name":"Rama Nayidu","paper1":"BA001/Geology","paper2":"","paper3":"","paper4":""}]
Doc: json_encode()
I have the following code that fetches arrays from a cURL.
$codici_hotel_arr = array();
foreach($data_destin['results'] as $key=>$val) {
$codici_hotel_arr[] = '"' . $val['hotel_code'] . '"';
$codici_price_arr[] = '"' . $val['products'][0]['price'] . '"';
}
$codici_definitivi = implode(', ', $codici_hotel_arr);
$codici_prezzi = implode(', ', $codici_price_arr);
The code returns these values:
**$codici_definitivi:**
"1074d0", "19f726", "1072ba", "183444", "1071bf", "112438", "1b326e", "15d8ab", "19d885", "193e61", "10aab2", "107155", "110669", "189b95", "16d78f", "18dd7d"
**$codici_prezzi**
"160.16", "234.32", "256.88", "325.42", "342.22", "353.30", "365.78", "372.84", "395.72", "478.75", "503.36", "543.39", "584.61", "584.61", "597.70", "601.63".
I would need to get a $codici_prezzi for each $codici_definitivi.
As a response of a string cURL, both codes are as follows:
1074d0 -> 160.16;
19f726 -> 234.32;
1072ba -> 256.88;
etc...
It's possible?
Thank you
If I don't misunderstood your requirement then this should work. Remove extra imploding and try to array_combine() the two corresponding arrays.
// Your initial code, after removing imploding
$codici_hotel_arr = $codici_price_arr = [];
foreach($data_destin['results'] as $key=>$val) {
$codici_hotel_arr[] = '"' . $val['hotel_code'] . '"';
$codici_price_arr[] = '"' . $val['products'][0]['price'] . '"';
}
// I assume your array structure will be after looping curl response
$codici_hotel_arr = ["1074d0", "19f726", "1072ba", "183444", "1071bf", "112438", "1b326e", "15d8ab", "19d885", "193e61", "10aab2", "107155", "110669", "189b95", "16d78f", "18dd7d"];
$codici_price_arr = ["160.16", "234.32", "256.88", "325.42", "342.22", "353.30", "365.78", "372.84", "395.72", "478.75", "503.36", "543.39", "584.61", "584.61", "597.70", "601.63"];
$result = array_combine($codici_hotel_arr,$codici_price_arr);
print '<pre>';
print_r($result);
print '</pre>';
Result:
Array (
[1074d0] => 160.16
[19f726] => 234.32
[1072ba] => 256.88
[183444] => 325.42
[1071bf] => 342.22
[112438] => 353.30
[1b326e] => 365.78
[15d8ab] => 372.84
[19d885] => 395.72
[193e61] => 478.75
[10aab2] => 503.36
[107155] => 543.39
[110669] => 584.61
[189b95] => 584.61
[16d78f] => 597.70
[18dd7d] => 601.63
)
Edit: Because I don't understand your expected result that's why I post it also.If you want it on string format then try like this,
function print_string($v, $k) {
echo "$k->$v\n";
}
array_walk($result, "print_string");
Supposing that the indices of the arrays are aligned, I would do this:
<?php
for($i = 0; $i < count($codici_definitivi); $i++) {
echo $codici_definitivi[0] . ' -> ' . $codici_prezzi[0];
// or set up any other mapping you need, e.g. key => value in another array
}
?>
Edit: you should place this mapping before the implode statements, otherwise you overwrite the original arrays with strings.
$new_codici_prezzi = array();
if(count($codici_definitivi) === count($codici_prezzi)){
for($i = 0; $i < count($codici_definitivi); $i++){
$new_codici_prezzi[$codici_definitivi[$i]] = $codici_prezzi[$i];
}
}
//After that, $new_codici_prezzi is your new array.
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
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]]}]
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]];
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.
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));
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);
i have data in set of groups
each group contains 3 Values As name , mobile , message.
How to store these multiple values in array and get echo of separate group .??
<?php
$full_name = array( );
$full_name["name"] = "john1";
$full_name["mobile"] = "923456812536";
$full_name["message"] = "message1";
$full_name["name"] = "john2";
$full_name["mobile"] = "565656565656";
$full_name["message"] = "message2";
$full_name["name"] = "john3";
$full_name["mobile"] = "444442222222222";
$full_name["message"] = "message3";
$full_name["name"] = "john4";
$full_name["mobile"] = "2222";
$full_name["message"] = "2222222222";
echo $full_name["name"]."</br>".
$full_name["mobile"]."</br>".
$full_name["message"]."</br></br>"
?>
Do your inserts into the array like:
$full_name[] = array(
"name" => "john1",
"mobile" => "923456812536",
"message" => "message1",
);
etc
to give yourself a multi-dimensional array
then loop using
foreach($full_name as $name) {
echo $name['name'], ' ', $name['mobile'], ' ', $name['message'], PHP_EOL;
}
You could use multi dimensional arrays like this
$full_name["name"][0] = "john1";
$full_name["mobile"][0] = "923456812536";
$full_name["message"][0] = "message1";
$full_name["name"][1] = "john2";
$full_name["mobile"][1] = "565656565656";
$full_name["message"][1] = "message2";
And echo a group like this
echo implode(", ", $full_name["name"]);
However, you need to make sure that ["name"][x] corresponds with ["mobile"][x] as these sub arrays are independent of each other. If you use Mark Baker's answer, you know that [x]["name"] belongs to the same person as [x]["mobile"]
This should work for you: With the [] it's going to insert the data into the next field of the array
<?php
$full_name = array( );
$full_name["name"][] = "john1";
$full_name["mobile"][] = "923456812536";
$full_name["message"][] = "message1";
$full_name["name"][] = "john2";
$full_name["mobile"][] = "565656565656";
$full_name["message"][] = "message2";
$full_name["name"][] = "john3";
$full_name["mobile"][] = "444442222222222";
$full_name["message"][] = "message3";
$full_name["name"][] = "john4";
$full_name["mobile"][] = "2222";
$full_name["message"][] = "2222222222";
print_r($full_name["name"]);
echo "</br>";
print_r($full_name["mobile"]);
echo "</br>";
print_r($full_name["message"]);
?>
How can I echo out value after the while loop. If I do the echo in below code its says Undefined index.
$sql_cast = "SELECT *
FROM
title_cast
INNER JOIN title ON (title_cast.id_title = title.id)
INNER JOIN `cast` ON (title_cast.id_cast = `cast`.id)
WHERE
title_cast.id_title = '1'";
$result_cast = mysql_query($sql_cast) or die('log error with' .mysql_error());
$cast = array();
while ($row = mysql_fetch_assoc($result_cast)) {
$id = $row['id'];
$name = $row['name'];
$img = $row['photo_localurl'];
$poster = str_replace("./", "lib/", $img);
$cast[] = array('id' => $id, 'name' => $name, 'img' => $poster);
//$cast[] = $row;
}
//var_dump($cast);
echo $cast['id'] . " " . $cast['name'] . " " . $cast['poster']."<br />";
Within the while loop, you set the cast array content using $cast[] syntax. This will create a numerical index, starting at 0, then 1 and so on, so you're creating an array that looks like this:
$cast = array(
0 => array('id' => $id, 'name' => $name, 'img' => $poster),
1 => array('id' => $id, 'name' => $name, 'img' => $poster)
);
You need to include the numerical key of the array that you want to echo. For example, if you want to echo the first row:
echo $cast[0]['id']; // Echo the id of the first result
If you want to echo ALL of the rows, use foreach:
foreach($cast as $row) {
echo $row['id'];
}
Maybe you should do:
$cast = array('id' => $id, 'name' => $name, 'img' => $poster);
//$cast[] = $row;
}
//var_dump($cast);
echo $cast['id'] . " " . $cast['name'] . " " . $cast['poster']."<br />";
because if you use $cast[], it will append the new array to your array..
That's because you are pushing a new array in $cast at each index..
So you should echo like this..
$i = 0;
while ($row = mysql_fetch_assoc($result_cast)) {
$id = $row['id'];
$name = $row['name'];
$img = $row['photo_localurl'];
$poster = str_replace("./", "lib/", $img);
$cast[] = array('id' => $id, 'name' => $name, 'img' => $poster);
//$cast[] = $row;
//var_dump($cast);
echo $cast[$i]['id'] . " " . $cast[$i]['name'] . " " . $cast[$i]['poster']."<br />";
$i++;
}
Try this:
<?php
while ($row = mysql_fetch_assoc($result_cast)) {
$id = $row['id'];
$name = $row['name'];
$img = $row['photo_localurl'];
$poster = str_replace("./", "lib/", $img);
$cast[] = array('id' => $id, 'name' => $name, 'img' => $poster);
}
foreach($cast as $rows) {
echo $rows['id']." ".$rows['name']." ".$rows['img']."<br />";
}
?>
print_r($cast[0]); or you can use $cast[0]['id'] ;
There are two problems with your code, First is that $cast[] is a two-dimensional array so it contains arrays at each of its index, so you must use
$cast[$i]['id']
Where i will be the counter variable that will iterate through all the indexes. Secondly change
$cast['poster']
to
$cast['img']
Hope this helps.