How to work with array JSON in php? - javascript

I'm a JavaScript Programmer and has a project with PHP.
I'm having trouble with working JSON with PHP.
This is my JSON
{
"orders":[
{
"name":"#1002"
},
{
"name":"#1001"
}
]
}
I need to get each name and echo them, I tried the following code $myarray = json_decode($order, true) but it returns me this error.
Warning: json_decode() expects parameter 1 to be string, array given in
How can i convert the json from array to string? or am i doing it wrong.

config.php
<?php
$con = mysql_connect('localhost','root','');
mysql_select_db('db_school',$con);
$sql = "SELECT * FROM userlogin";
$result = mysql_query($sql,$con);
$data = array();
while ($row = mysql_fetch_array($result)) {
$data[] =array(
'id'=>$row['id'],
'username'=>$row['username'],
'userpass'=>$row['userpass'],
);
}
echo json_encode(array('data'=>$data));
?>
view.php
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<table id="tbl" border="1">
<thead><tr>
<th>Id</th>
<th>Username</th>
<th>Password</th>
</tr></thead>
<tbody></tbody>
</table>
<script type="text/javascript">
$.ajax({
url: 'config.php',
}).done(function(res) {
var res_data = JSON.parse(res),table='';
$.each(res_data.data,function(index, el) {
console.log(el.id,' ', el.username,' ',el.userpass);
table+='<tr>';
table+='<td>'+el.id+'</td>';
table+='<td>'+el.username+'</td>';
table+='<td>'+el.userpass+'</td>';
table+='</tr>';
});
$('#tbl').html(table);
});
</script>
Demo:

Simply save the json response on a variable. And then do json_decode
$orders = '{
"orders":[
{
"name":"#1002"
},
{
"name":"#1001"
}
]
}';
$myarray = json_decode($orders, true);
Now performing print_r will yield result like
echo '<pre>';
print_r($myarray);
Result
Array
(
[orders] => Array
(
[0] => Array
(
[name] => #1002
)
[1] => Array
(
[name] => #1001
)
)
)
EDIT :
In order to get only name values simply run a foreach
$result = [];
foreach($myarray['orders'] as $value) {
$result[] = $value['name'];
}
Now printing $result you will get
Array
(
[0] => #1002
[1] => #1001
)

Related

How to replace the variable from controller to into a (.php) file

I have an empty test.php file,in that file, I've inserted data below shown.
This code is form controller. This trace data coming from UI using ajax.
Here my $trace array data like this :
array(
[0] => $test1 = "1,2,3,4,5,6,7";
[1] => $test2 = "1,2,3,4,7";
[2] => $test3 = "1,4,6,7,9,0";
)
This is coming from UI
$trace = $this->input->post('trace');
$viewsDir = 'C:/xampp/htdocs/project/application/views/html_v3/';
$fp = fopen($this->viewsDir.'test.php', 'w');
fwrite($fp, "<?php \n\n");
$i = 0;
if($trace){
foreach ($trace as $value) {
fwrite($fp, $trace[$i]."\n");
$i++;
}
}
fwrite($fp, "\n?>");
fclose($fp);
After inserted my data into test.php file then the file look like this:
<?php
$test1 = "1,2,3,4,5";
$test2 = "5,2,0,6,5";
$test3 = "4,8,9,7,1";
?>
Here, if once again I want to insert data into test.php file, my $trace array data like this:
aray(
[0] => $test1 = "9,9,9,9,9";
[1] => $test2 = "1,1,1,1,1";
[2] => $test4 = "1,2,6,7,8";
)
Here my query is how can I replace this ($trace)array variables if matched with test.php. If not matched it should be added to the test.php file.
Here my expected output is:
<?
$test1 = "9,9,9,9,9";
$test2 = "1,1,1,1,1";
$test3 = "4,8,9,7,1";
$test4 = "1,2,6,7,8";
?>
I tried like this,but i don't know how to compare my array($trace) and content of test.php
$file = $this->viewsDir.'test.php';
$contents = file_get_contents($file);
echo $contents; //i will get content of test.php based on this i have to replace or add
Please help me,
Thanks.
I'm not even sure I should help you with that. There is possibly something very wrong with your design if you're passing php code via POST and save it to a source file.
Anyways...
I'd declare helper function that 'parses' entry string line as key $trace1 and value "1,2,3,4,5" and adds it to array $arr
function addToTrace(&$arr, $entry) {
$entry = trim($entry);
if(substr($entry, 0, 1) == "$") {
$elements = explode("=", $entry);
if(count($elements) !== 2) {
return false;
}
$elements = array_map('trim', $elements);
$arr[$elements[0]] = $elements[1];
return true;
}
return false;
}
After that it's only a matter of reading the file first, adding all entries to new array $currTrace
$currTrace = [];
$fp = fopen($this->viewsDir . 'test.php', 'r');
if($fp) {
while (!feof($fp)) {
$line = fgets($fp);
addToTrace($currTrace, $line);
}
fclose($fp);
}
than adding new trace from post (ovewriting matching keys):
if($trace){
foreach ($trace as $value) {
addToTrace($currTrace, $value);
}
}
and saving $currTrace to file:
$fp = fopen($this->viewsDir . 'test.php', 'w');
fwrite($fp, "<?php \n\n");
foreach($currTrace as $key => $value) {
fwrite($fp, $key . " = " . $value . "\n");
}
fclose($fp);

Google Charts Dynamic Arrays PHP Without SQL

I'm asking this question because all the answers I could find for similar problems were using MySQL whereas I'm not, just a JSON API to get the data, which I then put into arrays that I want to display as a Google graph. All I know is that I have to somehow format the arrays properly in order to get them to display but I have no idea how to do it in my case. I would just like to have a simple pie chart, based on the arrays below. So far I'm getting a blank space on the site. I tried something with Json_encode before but it didn't work so I decided to leave it as it is and come here instead. Here are the arrays after I do print_r:
Array 'name'-
Array ( [0] => Facebook Inc [1] => Alphabet Class A [2] => Apple Inc [3] => Ford Motor Company [4] => Adv Micro Devices [5] => Morgan Stanley [6] => Berkshire Hath Hld B [7] => JP Morgan Chase & Co )
Array 'sumOf'-
Array ( [0] => 5811.63 [1] => 116135.97 [2] => 1564.1 [3] => 1053 [4] => 113.1 [5] => 521.4 [6] => 1960.2 [7] => 1100.4 )
Code:
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script type="text/javascript">
google.charts.load('current', {'packages':['corechart']});
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
var data = google.visualization.arrayToDataTable($name, $sumOf);
var options = {
title: 'Portfolio Allocation'
};
var chart = new google.visualization.PieChart(document.getElementById('piechart'));
chart.draw(data, options);
}
</script>
<body>
<div id="piechart" style="width: 900px; height: 500px;"></div>
</body>
How arrays are made:
$name = [];
$lastprice = [];
$y = 0;
$z = '';
$key = "";
// Retreiving information from database
$memberid = $_SESSION['memberID'];
$sql = "SELECT * FROM portfolio WHERE memberID = $memberid";
$result = mysqli_query($conn, $sql);
// Check if databse is empty
if (mysqli_num_rows($result) > 0)
{
while($row = mysqli_fetch_assoc($result))
{
$sym[$y] = $row["stocks_symbol"];
$pri[$y] = $row["price"];
$vol[$y] = $row["quantity"];
$id[$y] = $row["memberid"];
$y += 1;
}
}
// If database empty
else
{
echo "Portfolio Empty";
die();
}
mysqli_close($conn);
// Adding all stock names in one variable to enable API call
for($a=0;$a<$y;$a++)
{
$z = $z.$sym[$a].',';
}
$z = rtrim($z,",");
// API call
$contents = file_get_contents("http://marketdata.websol.barchart.com/getQuote.json?key=$key&symbols=$z&mode=R");
$contents = json_decode($contents, true);
// Check successfull API call
if($contents["status"]["code"] == 200)
{
foreach($contents['results'] as $result)
{
array_push($name,$result['name']);
array_push($lastprice,$result['lastPrice']);
}
}
// If API call unsuccessful
else
{
echo "Error retreiving data. Please try again later.";
die();
}
?>
<!-- Generating Output in tabular format -->
<table id= test class='table table-responsive'>
<tr class='head warning'>
<th>Name</th>
<th>Last Price</th>
<th>Price Bought</th>
<th>Quantity</th>
<th>Change Per Stock</th>
<th>Profit/Loss</th>
<th>Market Value</th>
<th>Amount Invested</th>
</tr>
<?php
$profitOrLossSum = 0;
$dividendRateSum = 0;
$startEqSum = 0;
$sumOf = array();
for($x=0;$x<$y;$x++)
{?>
<tr>
<td class="input"><?php echo $name[$x]; ?></td>
<td class="input"><?php echo $lastprice[$x]; ?></td>
<td class="input"><?php echo $pri[$x]; ?></td>
<td class="input"><?php echo $vol[$x]; ?></td>
<td class="input"><?php
if($pri[$x] > $lastprice[$x])
{
echo $lastprice[$x]-$pri[$x];
}
else if($pri[$x] < $lastprice[$x])
{
echo $lastprice[$x]-$pri[$x];
}
else
echo '0';
?></td>
<td class="input"><?php
$profitOrLoss = ($lastprice[$x]-$pri[$x]) * $vol[$x];
$profitOrLossSum += $profitOrLoss;
echo $profitOrLoss;
?></td>
<td><?php
$firstno1 = floatval($vol[$x]);
$secondno1 = floatval($lastprice[$x]);
$sumOf[] = $firstno1 * $secondno1;
$sum1 = $firstno1 * $secondno1;
print ($sum1);
?></td>
<td class="input">
<?php
$starteq = $pri[$x] * $vol[$x];
$startEqSum += $starteq;
echo $starteq;
?>
</td>
</tr>
<?php
}
$arr = array('profitOrLossSum' => $profitOrLossSum, 'dividendRateSum' => $dividendRateSum);
$arr1 = array('startEqSum' => $startEqSum);
print_r ($name);
print_r ($sumOf);
echo json_encode($name);
echo json_encode($sumOf);
?>
Here is the working Example of your code you were very close though. Actually, you have to pass only one single parameter as a multidimensional array to arrayToDataTable(); you have to json_encode and JSON_parse your array as well
check https://developers.google.com/chart/interactive/docs/gallery/piechart
No worries its working copy and paste it and you are good to go.
<?php
$name = ['Facebook Inc', 'Alphabet Class A', 'Apple Inc', 'Ford Motor Company', 'Adv Micro Devices', 'Morgan Stanley', 'Berkshire Hath Hld B', 'P Morgan Chase & Co'];
$sumOf = [5811.63, 116135.97, 1564.1, 1053, 113.1, 521.4, 1960.2, 1100.4];
?>
<html>
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script type="text/javascript">
google.charts.load('current', {'packages': ['corechart']});
google.charts.setOnLoadCallback(drawChart);
var name = <?= json_encode($name) ?>;
var sumOf = <?= json_encode($sumOf) ?>;
var array = name.split(",");
newArr = [['Name', 'Amount']];
array.forEach(function (v, i) {
newArr.push([v, sumOf[i]]);
});
function drawChart() {
var data = google.visualization.arrayToDataTable(newArr);
var options = {
title: 'Portfolio Allocation'
};
var chart = new google.visualization.PieChart(document.getElementById('piechart'));
chart.draw(data, options);
}
</script>
<body>
<div id="piechart" style="width: 900px; height: 500px;"></div>
</body>
</html>
array_combine was needed to join the two arrays together and then inside of
'function drawChart' a simple foreach loop was required, like this:
<?php
foreach ($array as $name => $allocation):
echo "['$name', $allocation]";
echo ($allocation != end($array)) ? ',' : '';
endforeach;
?>

$.getJSON with php file

Hi guys :) I'm quite new in the programming world, so I really need your help. I tryed to get data from some database tables and unfortunately something goes wrong in my $.getJson() function . If i run the php file it works , and so that with the functions from script.js . My html is also ok so i suppose it is the $get.JSON fault. I don't know so many javascript , so i put all my hopes into you :*
html file:
<!doctype html>
<html>
<head>
<meta charset="utf-8" />
<title>jQuery Ajax - PHP</title>
<script type="text/javascript" src="jquery.js"></script>
</head>
<body>
<script src="script.js">
</script>
</body>
</html>
script.js file :
$('document').ready( function() {
done();
}
);
function done() {
setTimeout(function() {
updates();
done();
}
, 200 );
}
function updates(){
$.getJSON( "read.php", function (data){
$.each(data.array, function () {
$("body").append("<li>Titlu: "+this['title']+"</li>
<li>Descriere: "+this['describtion']+"</li>");
}
);
$.each(data.array1, function () {
$("body").append("<li>Id: "+this['id']+"</li>
<li>Category_Id: "+this['category_id']+"</li>
<li>Titlu: "+this['title']+"</li>
<li>Descriere: "+this['describtion']+"</li>");
}
);
$.each(data.array2, function () {
$("body").append("<li>Id: "+this['id']+"</li>
<li>Titlu: "+this['title']+"</li>
<li>Latitudine: "+this['location_latitude']+"</li>
<li>Longitudine:"+this['location_longitude']+"</li>
<li>Numar de telefon: "+this['phone_number']+"</li>
<li>Descriere: "+this['describtion']+"</li>");
}
);
$.each(data.array3, function () {
$("body").append("<li>Id: "+this['id']+"</li>
<li>Interest_point_id:"+this['interest_point_id']+"</li>
<li>Pret: "+this['price']+"</li>
<li>Data: "+this['event1_time']+"</li>");
}
);
}
);
}
And finally the read.php file (Here it shows me what i expect , so i think everything is all right) :
<?php
include_once ('db.php');
$query= "SELECT * FROM category";
$query1= "SELECT * FROM sub_category";
$query2= "SELECT * FROM interest_point";
$query3= "SELECT * FROM event1";
global $connect;
$result = mysqli_query($connect,$query);
$result1 = mysqli_query($connect,$query1);
$result2 = mysqli_query($connect,$query2);
$result3 = mysqli_query($connect,$query3);
$array = array();
$array1 = array();
$array2 = array();
$array3 = array();
while($row=mysqli_fetch_array($result))
array_push($array , array( 'id' => $row[0],
'title' => $row[1],
'describtion' => $row[2]
));
while($row1=mysqli_fetch_array($result1))
array_push($array1 , array( 'id' => $row1[0],
'category_id' => $row1[1],
'title' => $row1[2],
'describtion' => $row1[3]
));
while($row2=mysqli_fetch_array($result2))
array_push($array2 , array('id' => $row2[0],
'title' => $row2[1],
'location_latitude' => $row2[2],
'location_longitude'=> $row2[3],
'phone_number' => $row2[4],
'describtion' => $row2[5]
));
while($row3=mysqli_fetch_array($result3))
array_push($array3 , array(
'id' => $row3[0],
'interest_point_id'=> $row3[1],
'price' => $row3[2],
'event1_time' => $row3[3]
));
echo json_encode(array("array"=>$array)).'<br>'.'<br>';
echo json_encode(array("array1"=>$array1)).'<br>'.'<br>';
echo json_encode(array("array2"=>$array2)).'<br>'.'<br>';
echo json_encode(array("array3"=>$array3)).'<br>'.'<br>';
?>
You can only echo once when sending json and there can only be one php array containing all the data. You can't print anything outside of this such as the <br> tags
try changing
echo json_encode(array("array"=>$array)).'<br>'.'<br>';
echo json_encode(array("array1"=>$array1)).'<br>'.'<br>';
echo json_encode(array("array2"=>$array2)).'<br>'.'<br>';
echo json_encode(array("array3"=>$array3)).'<br>'.'<br>';
To
$output = array(
"array1"=>$array1,
"array2"=>$array2,
"array3"=>$array3
);
echo json_encode($output);
Also note that <li> is an invalid child of <body>. Use <div> or insert into a <ul>

How to convert a JSON to an array which can be used to bind values in a dropdown list?

I have an application where I can generate JSON, which in turn I use as input to GoogleCharts API to draw different visualizations. The pages of this web application are in HTML.
Suppose I have a JSON which has a list of departments of a hospital, like: [{"v":"General Medicine"},{"v":"Laboratory"}]
How do I use Javascript to convert this to an array which in turn can be used as option values of a drop down list?
I am using the following code to generate JSON:
<?php
$serverName = "forestroot"; //serverName\instanceName
$connectionInfo = array( "Database"=>"****", "UID"=>"****", "PWD"=>"****");
$conn = sqlsrv_connect( $serverName, $connectionInfo);
if( $conn ) {
//echo "Connection established.<br />";
}else{
echo "Connection could not be established.<br />";
die( print_r( sqlsrv_errors(), true));
}
$sql = "SELECT distinct([DEPT_NAME]) as dept FROM [Pristine11Dec15].[dbo]. [PACKAGE_REVN]";
$params = array();
$options = array( "Scrollable" => SQLSRV_CURSOR_KEYSET );
$result = sqlsrv_query( $conn, $sql, $params, $options);
if (sqlsrv_num_rows( $result ) > 0) {
while($row = sqlsrv_fetch_array($result, SQLSRV_FETCH_ASSOC)) {
$array[] = array('v'=>$row["dept"]);
}
}
echo json_encode($array);
sqlsrv_close( $conn);
?>
The output is [{"v":"General Medicine"},{"v":"Laboratory"}]
When I use JSON.parse in my code I am getting the options as [object Object] in the drop down list. Where am I going wrong?
var json = '[{"v":"General Medicine"},{"v":"Laboratory"}]';
Parse the data and use map to return an array of v values:
var list = JSON.parse(json).map(function (el) {
return el.v;
}); // [ "General Medicine", "Laboratory" ]
DEMO
You could extend this however to build up the HTML for the select:
var templ = '<option value="#{el}">#{el}</option>';
var options = JSON.parse(json).map(function (el) {
return templ.replace('#{el}', el.v, 'g');
}).join('');
var select = '<select>' + options + '</select>';
document.getElementById('menu').insertAdjacentHTML('beforeend', select);
DEMO

Alternative for JSON_ENCODE to be called in d3js graph

I need to plot d3.js histogram and i have troube in plotting the data from database.
php code is as follows.
<?php
// Create connection
$con=mysqli_connect("localhost","","","a");
// Check connection
if (mysqli_connect_errno($con))
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,"SELECT `b` FROM `h` LIMIT 1");
while($row = mysqli_fetch_array($result))
{
$s1[] = $row['b'];
$length=count($s1);
for($i=0;$i<$length;$i++)
{
$a = array(preg_replace("([c]+)", "",$s1[$i] ));
$b=(str_replace(array( '(', ')') , '', $a));
print_r($b);
$p=implode(" ",$b);
print_r($p);
$co=array_map('strval', explode(',', $p));
echo '</br>'."my array";
print_r($co);
}
}
$result1 = mysqli_query($con,"SELECT `a` FROM `h` LIMIT 1");
while($row1 = mysqli_fetch_array($result1))
{
$s2[] = $row1['a'];
$length1=count($s2);
for($j=0;$j<$length1;$j++)
{
$a1 = array(preg_replace("([c]+)", "",$s2[$j] ));
$b1=(str_replace(array( '(', ')') , '', $a1));
print_r($b1);
$p1=implode(" ",$b1);
print_r($p1);
$co1=array_map('strval', explode(',', $p1));
echo '</br>'."my array2..........";
print_r($co1);
}
}
$map=array_map(null,$co1,$co);
echo "<br>";
echo JSON_ENCODE($map);
echo "<br>";
$object = new stdClass();
$length5=count($s2);
// echo "lennnnnnnnn".$length5;
for($l=0;$l<7;$l++) {
foreach ($map[$l] as $key => $value)
{
if($key == 0)
$object -> a = $value;
else if($key == 1)
$object -> b = $value;
}
$newArr[$l] = JSON_ENCODE($object);
}
print_r($newArr);
mysqli_close($con);
?>
printing array using,
print_r($newArr);
displays the following,
Array ( [0] => {"a":"26.5","b":"80"} [1] => {"a":" 27","b":" 222"} [2] => {"a":" 27.5","b":" 303"} [3] => {"a":" 28","b":" 408"} [4] => {"a":" 28.5","b":" 276"} [5] => {"a":" 29","b":" 151"} [6] => {"a":" 29.5","b":null} )
in d3js code,
var bins = <?php echo JSON_ENCODE($newArr) ; ?>;
bins.forEach(function(bin) {
bin.a = +bin.a;
bin.b = +bin.b;
});
displays the following,
["{\"a\":80,\"b\":26.5}","{\"a\":222,\"b\":27}"," {\"a\":303,\"b\":27.5}","{\"a\":408,\"b\":28}","{\"a\":276,\"b\":28.5}","{\"a\":151,\"b\":29}"," {\"a\":null,\"b\":29.5}"]
I need to call this output in my d3.js code using echo json_encode. When using this, the data creates forward slashes "\" with the numbers and so the numbers are not read as input for the graph. Is there any way to remove the slashes or to take the data with any other alternate code or function?
thanks in advance.
You didn't provide a complete example, but it looks like you're double json_encodeing. You json_encode array of already json_encoded values.

Categories

Resources