Good day,
I have this data which I got from my query on PHP its is currently a JSON Format, now I want to convert it into array so I can use it on my pdf. How can I do this?
so in order for me to use it on my javascript I used
var inventory = <?php echo json_encode($inventory); ?> ;
my JSON data :
var inv = [
{"xid":96,"xitem":"CARBOCISTEINE 500MG CAP (MYREX) BOX",
"itemId":852,
"price":3,
"mprice":3
},
{"xid":253,"xitem":"CIPROFLOXACIN 500MG TAB (PROSELOC\/FLAMINGO)",
"itemId":1165,
"price":0,
"mprice":0
}];
I tried
var rows = <?php echo json_encode($inventory); ?> ;
var arr = $.map(rows, function(el) { return el; });
and
when I console.log(arr);
I still get the object structure not the array structure that I wanted.
I also tried
var result = [];
for(var i in rows)
result.push([i, rows [i]]);
console.log(result);
but it gives me
[ ["0",Object { xid=96,xitem="CARBOCISTEINE 500MG CAP (MYREX) BOX",itemId=852,price=3,mprice=3}],
["1",Object{etc..}]];
instead
I want it to have a structure like
[96,"CARBOCISTEINE 500MG CAP (MYREX) BOX",852,3,3],
[253,"CIPROFLOXACIN 500MG TAB (PROSELOC\/FLAMINGO)",1165,0,0]
Is there something I am missing on my code or How should I be able to do this? thanks..
You can use this:
var arr = inv.map(function (obj) { return [obj.xid, obj.xitem, obj.itemId, obj.price, obj.mprice]})
console.log(arr);
If you do small changes to your map callback function, then it will be fine.
you can do just
class MyClass
{
public $var1 = 'value 1';
public $var2 = 'value 2';
public $var3 = 'value 3';
}
$class = new MyClass();
$arr = [];
foreach($class as $key => $value) {
$arr[] = $value;
}
echo json_encode($arr); //here's to check
in PHP - you can make a collection of object like this and iterate first oveer this collection to get result as you wanted to have
You shouldn't have to hard code the keys. The following works:
var arrayFromObject = inv.map(function (item) {
var arr = [];
for (var p in item) arr.push(item[p])
return arr;
});
Related
How to make a JSON string into a javascript object. I am trying to convert the following string into JSON Object like this that is getting from the server
JSON String:
["{"title":"Admin Dhaka","href":"#0","dataAttrs":[],"data":["{\"title\":\"BNS HAJI MOHSIN\",\"href\":\"#0\",\"dataAttrs\":[\"{\\\"title\\\":\\\"id\\\",\\\"data\\\":\\\"51\\\"}\"]}","{\"title\":\"BNS ISSA KHAN\",\"href\":\"#1\",\"dataAttrs\":[\"{\\\"title\\\":\\\"id\\\",\\\"data\\\":\\\"1\\\"}\"]}","{\"title\":\"BNT KHADEM\",\"href\":\"#2\",\"dataAttrs\":[\"{\\\"title\\\":\\\"id\\\",\\\"data\\\":\\\"6\\\"}\"]}","{\"title\":\"BN DOCKYARD\",\"href\":\"#3\",\"dataAttrs\":[\"{\\\"title\\\":\\\"id\\\",\\\"data\\\":\\\"13\\\"}\"]}","{\"title\":\"BNT SEBAK\",\"href\":\"#4\",\"dataAttrs\":[\"{\\\"title\\\":\\\"id\\\",\\\"data\\\":\\\"7\\\"}\"]}","{\"title\":\"Naval Aviation\",\"href\":\"#5\",\"dataAttrs\":[\"{\\\"title\\\":\\\"id\\\",\\\"data\\\":\\\"89\\\"}\"]}","{\"title\":\"BNS SAIKAT\",\"href\":\"#6\",\"dataAttrs\":[\"{\\\"title\\\":\\\"id\\\",\\\"data\\\":\\\"40\\\"}\"]}","{\"title\":\"BNS Novojatra\",\"href\":\"#9\",\"dataAttrs\":[\"{\\\"title\\\":\\\"id\\\",\\\"data\\\":\\\"119\\\"}\"]}","{\"title\":\"BNS SHAH AMANAT\",\"href\":\"#10\",\"dataAttrs\":[\"{\\\"title\\\":\\\"id\\\",\\\"data\\\":\\\"11\\\"}\"]}"]}"]
As an example, I have given one object in the above code actually the Array is a list of Objects like this
[obj1, obj2....]
I tryed as follows:
var arr = '<?php echo !empty($treeView) ? $treeView : "[]"; ?>';
arr = JSON.parse(arr);
console.log(arr);
Getting the following error:
Uncaught SyntaxError: Unexpected token t in JSON at position 4
PHP Code:
function ship_by_area_zone(){
$area_list = [];
$ship_list = [];
$zone = $this->utilities->findAllByAttributeWithOrderBy("bn_navyadminhierarchy", array("ADMIN_TYPE" => 1, "ACTIVE_STATUS" => 1), "CODE");
$area = $this->utilities->findAllByAttributeWithOrderBy("bn_navyadminhierarchy", array("ADMIN_TYPE" => 2, "ACTIVE_STATUS" => 1), "CODE");
// area wise ship
foreach ($area as $key=>$value)
{
$row = $this->db->query("select * from bn_ship_establishment where AREA_ID = $value->ADMIN_ID and ACTIVE_STATUS = 1 order by CODE asc")->row();
if($row)
{
$dataAttrs = array();
$dataAttrs['title'] = 'id';
$dataAttrs['data'] = $row->SHIP_ESTABLISHMENTID;
$dataAttrs = json_encode($dataAttrs);
$ship_row = array();
$ship_row['title'] = $row->NAME;
$ship_row['href'] = "#$key"; //"#1"
$ship_row['dataAttrs'] = [$dataAttrs];
$ship_list[] = json_encode($ship_row);
}
}
// zone wise area
foreach ($zone as $key=>$value)
{
$row = $this->db->query("select * from bn_navyadminhierarchy where ACTIVE_STATUS = 1 and PARENT_ID = $value->ADMIN_ID order by CODE asc")->row();
if($row)
{
$area_row = array();
$area_row['title'] = $row->NAME;
$area_row['href'] = "#$key";
$area_row['dataAttrs'] = [];
$area_row['data'] = $ship_list;
$area_list[] = json_encode($area_row);
}
}
return json_encode($area_list);
}
Can anyone help me?
Thanks in advance!
You need to use json_encode in your PHP:
var arr = '<?php echo json_encode(!empty($treeView) ? $treeView : "[]"); ?>';
First of all, the json string you have there is invalid. You can check free online to validate the json. Once you have a valid json, you can use JSON.parse() to convert it to JSONObject
// converting a simple javascript object to JSON object
my_details =
{
"name" : "SL",
"age " : "30" ,
"photo" : "imgMe.jpg"
}
my_details_in_json = JSON.stringify(my_details);
// "{"name":"SL","age ":"30","photo":"imgMe.jpg"}" --> my_details_in_json
How can I convert an array of arrays to a single array in Vue.js? In my php back-end, I have the code below that fetch data from database. My problem now is I don't know how to convert them in my js side to a single array.
PHP side:
$name = DB::raw("CONCAT(emp.first_name, ' ', emp.last_name) AS name");
$nameCol = [];
$usedDate = '2018-07';
$date = 'attendance.date';
$total = 'attendance.total';
for($i = 1; $i<32; $i++){
if($i<10) $i = '0'.$i;
$names = DB::table('attendance')
->leftJoin('m_emp','m_emp.emp_key','=','attendance.emp_key')
->select($name,$date,$total)
->where(DB::raw("(DATE_FORMAT(attendance.date,'%Y-%m-%d'))"), '=', $usedDate.'-'.$i)
->get();
array_push($nameCol,$names);
}
return (array)$nameCol;
Result is like this:
Inside of each array is like this:
And finally inside it is this:
Can I do for loop on it to transform it to a single array and how? Or can I right away search for an item inside it? Because I have tried search using a way like this but I think this only search or works in a single array (that's my reason why I want to merge them to one array):
Vue.js side
list.find( empName=> empName.name === 'John Doe')
//let's assume list is the variable that receives data returned from php
//result for this one is undefined.
Any idea how ?
You can use array_merge instead of array_push.
I guess you are using Laravel , you have to convert the collection to array before merging that, see the example :
$name = DB::raw("CONCAT(emp.first_name, ' ', emp.last_name) AS name");
$nameCol = [];
$usedDate = '2018-07';
$date = 'attendance.date';
$total = 'attendance.total';
for($i = 1; $i<32; $i++){
if($i<10) $i = '0'.$i;
$names = DB::table('attendance')
->leftJoin('m_emp','m_emp.emp_key','=','attendance.emp_key')
->select($name,$date,$total)
->where(DB::raw("(DATE_FORMAT(attendance.date,'%Y-%m-%d'))"), '=', $usedDate.'-'.$i)
->get();
// use array_merge
$nameCol = array_merge($nameCol,$names->toArray());
}
return (array)$nameCol;
What I am trying to do doesn't feel difficult, but for some reason I can't seem to find the correct way to ouput this JSON array, from php.
PHP code:
$a = array();
$i=0;
while($row = mysqli_fetch_array($result))
{
$i++;
$a = array();
$epoch = $row['time'];
$dt = new DateTime("#$epoch"); // convert UNIX timestamp to PHP DateTime
$a = array(
"time" => $dt->format('Y-m-d H:i:s'),
"signal" => $row['signal'],
"symbol" => $row['symbol'],
"price" => $row['price'],
"timeframe" => $row['timeframe'],
"epoch" => $row['time']);
echo json_encode($a, JSON_UNESCAPED_SLASHES);
}
Output:
{
"time":"2016-11-14 17:23:00",
"signal":"Sell",
"symbol":"XAUUSDecn",
"price":"1221.64000",
"timeframe":"M1",
"epoch":"1479144180"
}
{
"time":"2016-11-14 17:07:59",
"signal":"Sell",
"symbol":"GBPJPYecn",
"price":"135.13200",
"timeframe":"M1",
"epoch":"1479143279"
}
The correct output should have },{ NOT }{ between each object.
What I am ultimately trying to do:
function getTrades(a) {
$.ajax({ //create an ajax request to load_page.php
type: "GET",
url: "core/engine.php",
data: "q=data&account="+a,
dataType: "html", //expect html to be returned
success: function(response){
if(response=="nologin") {
alert("Sorry, but either your account is not activated or your login is incorrect!");
} else {
var j = $.parseJSON(response);
$.each(j, function (k, v) {
$("#trades").html('<span class="tradesignal"><!-- span class="signalarrowup"></span-->'+v.time+'<span style="color:#2DC14E;"> '+v.signal+'</span> <button class="tsym" id="sym_'+v.epoch+'">'+v.symbol+'</button> '+v.price+' '+v.timeframe+'</span>');
});
}
//alert(response);
console.log(response);
}
});
}
Each {json},{json} object will have its data printed into a span on an html page.
Appreciate the guidance!
Try creating a results array and push each one of the objects there, then after the loop finishes, convert the array to json and print it.
example:
$results = array();
$i = 0;
while($row = mysqli_fetch_array($result)){
//your code here
$a = array("time" => ....);
$results[] = $a; //this will add $a to $results
}
echo json_encode($results, JSON_UNESCAPED_SLASHES);
Just to add a little more explanation in addition to the code the other answers are suggesting. The problem is, you aren't outputting a JSON array. Each time you do
echo json_encode($a, JSON_UNESCAPED_SLASHES);
inside your loop, you output a valid JSON object like:
{
"time":"2016-11-14 17:23:00",
"signal":"Sell",
"symbol":"XAUUSDecn",
"price":"1221.64000",
"timeframe":"M1",
"epoch":"1479144180"
}
However, when you output the subsequent objects, getting a result like
{
"time": ...
}
{
"time": ...
}
You no longer have valid JSON. Even though each of the individual objects is valid, concatenating them together isn't. Simply adding a comma between the objects will still not make it valid. In order to produce an actual JSON array, the comma separated objects will need to be enclosed in square brackets like this:
[
{
"time": ...
},
{
"time": ...
}
]
That's why you need to add each of the arrays you're creating in the loop to an outer array and then json_encode the whole thing after the loop. The outer PHP array will become the outer JSON array you need.
As Xorifelse said, you want to put the data in an array, and then call json_encode on the array. Here is a code that should work:
$a = array();
$i=0;
while($row = mysqli_fetch_array($result))
{
$i++;
$epoch = $row['time'];
$dt = new DateTime("#$epoch"); // convert UNIX timestamp to PHP Date
$a[] = array("time" => $dt->format('Y-m-d H:i:s'), "signal" => $row['signal'], "symbol" => $row['symbol'], "price" => $row['price'], "timeframe" => $row['timeframe'],"epoch" => $row['time']);
}
echo json_encode($a, JSON_UNESCAPED_SLASHES);
I have array from database with json_encode, like this :
"[{"uid":"595e7d","name":"Elephant"},{"uid":"701b03","name":"Bird"},{"uid":"29a8c","name":"Lion"}]"
but how to make the array just display the record not with the field/column name, when i show in javascript like this :
javascript array :
{
"595e7d": "Elephant",
"701b03": "Bird",
"29a8c": "Lion"
}
whether it should be done in php or javascript?
thankyou
Handle with javascript:
function transfrom (arrs){
return arrs.reduce((init, arr) => {
init[arr.uid] = arr.name
return init
}
, {})
}
//usage
let arrs = [{"uid":"595e7d","name":"Elephant"},{"uid":"701b03","name":"Bird"},{"uid":"29a8c","name":"Lion"}]
transfrom(arrs)
// {595e7d: "Elephant", 701b03: "Bird", 29a8c: "Lion"}
Or you can handle it with PHP:
<?php
$arr = array (
array('uid' =>"595e7d", "name"=>"Elephant"),
array("uid" =>"701b03", "name" =>"Bird"),
array("uid" =>"29a8c", "name" =>"Lion")
);
function transform($v1, $v2) {
$v1[$v2["uid"]] = $v2["name"];
return $v1;
}
echo json_encode(array_reduce($arr, "transform", array()));
// {
// "595e7d": "Elephant",
// "701b03": "Bird",
// "29a8c": "Lion"
// }
?>
If I understood it correctly, you are looking for something like
var arr = [{"uid":"595e7d","name":"Elephant"},{"uid":"701b03","name":"Bird"},{"uid":"29a8c","name":"Lion"}];
var out = {};
arr.forEach(function(obj){
var tempArr = Object.values(obj);
out[tempArr[0]] = tempArr[1];
});
console.log(out);
Please note that the code is not too generic and may require modification based on your actual requirement.
I have this array value: print_r ($array); which contains 2 data (this is latt and long of my gmap project).
The array is from:
<?php
if(isset($_GET['q'])) {
$q = $_GET['q'];
}
$q = isset($_GET['q']) ? $_GET['q'] : '';
$array = array();
$nsUser="SELECT * FROM cliententry WHERE kampusterdekat=:q";
$uQuery = $mydb->prepare ($nsUser);
$uQuery->execute(array(':q' => $q));
while ($result = $uQuery->fetch(PDO::FETCH_ASSOC)) {
$id=$result['id'];
$googlemap=$result['googlemap'];
//echo $googlemap;
$array[] = $googlemap;
print_r ($array);
}
?>
When I echo, the result will be like this:
Array
(
[0] => -5.364000343425874, 105.24465411901474
)
Array
(
[0] => -5.364000343425874, 105.24465411901474
[1] => -5.362878747789552, 105.24150252342224
)
Point:
What I need is to make the result into this format:
var wwwsitus = [
['<h4>area</h4>', wwwsitus[0]],
['<h4>area</h4>', wwwsitus[1]],
];
where locations (<h4>area</h4>) are removed. So, it must be, as follows:
var wwwsitus = [
[...,...],
[...,....],
];
Note:
Since I've no capable about array in JS, please help me to fix my title based on my issue. Thks in adv.