I am creating a multidimensional array via an Ajax call to populate a Google Chart (Column). However the Array that is getting returned is causing this error:
Uncaught Error: Not a valid 2D array.
This is the code that generates the array to send back:
$chartData = array();
$i = 0;
foreach ($hourVal as $value) {
if($i <= 9){
$chartData[] = array(
"0" . $i => (int) $value
);
} else {
$chartData[] = array(
$i => (int) $value
);
}
$i++;
}
This is the array when I console.log:
[
[
"Terms",
"Visits"
],
{
00: 88
},
{
01: 30
},
{
02: 44
},
{
03: 20
}
]
EDIT: I add a row at the beginning of the array and also json_encode:
array_unshift($chartData, array("Terms","Visits"));
echo json_encode($chartData);
Any ideas what is going on and how I can fix this?
That's not a 2D array. it's an array of objects (and one array). When you do json_encode, you only get an array if your PHP array is a numeric one (indexed starting at 0). Otherwise you get an object (since JavaScript/JSON doesn't have "associative arrays").
You need to make sure your array is numeric and indexed starting from 0.
$chartData = array();
$i = 0;
foreach ($hourVal as $value) {
$chartData[] = array(
$i => (int) $value
);
$i++;
}
I don't know why you were doing "0" . $i, but that's what was causing your problem. That was creating an "associative array", which encodes as an object.
I have solved it, its because I was sending them through with a prefix of 0 and then it was making them the index of the array. Had to cut that bit out and send as string. Not desired but a fix :(
Related
I have sent data from my php script using `json_encode' function.
if I console.log(resp) below is the O/P I get.
data: "{"dept_name":"IT","city_name":"Mumbai","emp_id":"#AC001","emp_name":"Akshay S. Shrivastav"}
{"dept_name":"IT","city_name":"Mumbai","emp_id":"#AC003","emp_name":"Aakash Shrivastav"}" status: "success"
however, if I console.log(resp.data) I get the below data
{"dept_name":"IT","city_name":"Mumbai","emp_id":"#AC001","emp_name":"Akshay S. Shrivastav"}{"dept_name":"IT","city_name":"Mumbai","emp_id":"#AC003","emp_name":"Aakash Shrivastav"}
Now I'm trying to display this data in the data tables for which I am using the below code.
$('#grpList').DataTable().row.add([
resp.data.dept_name,
resp.data.city_name,
resp.data.emp_id,
resp.data.emp_name
]).draw(false);
I'm receiving the following error
DataTables warning: table id=grpList - Requested unknown parameter '0' for row 0, column 0. For more information about this error, please see http://datatables.net/tn/4
when I am single handed displaying only console.log(resp.data.dept_name) it says undefined
I'll be having multiple JSON response if the data increases, for now, I only have two. I'm not able to figure out how to display multiple data using a loop and appending it to the data table.
I'm using below php code to generate JSON
$jsonArray = "";
if($data->num_rows > 0)
{
while($row = $data->fetch_assoc())
{
$jsonArray .= json_encode(
array(
"dept_name" => $row['department_name'],
"city_name" => $row['city_name'],
"emp_id" => $row['emp_id'],
"emp_name" => $row['name']
));
}
echo json_encode(array("data" => $jsonArray, "status" => 'success'));
}
Because resp.data is an array of objects. You need to get the index first - let's say index 0, or the first object in the array:
$("#grpList").DataTable().row.add([
resp.data[0].dept_name,
resp.data[0].city_name,
resp.data[0].emp_id,
resp.data[0].emp_name
]).draw(false);
And if you want the second object:
$("#grpList").DataTable().row.add([
resp.data[1].dept_name,
resp.data[1].city_name,
resp.data[1].emp_id,
resp.data[1].emp_name
]).draw(false);
Of course, row.add() accepts an array argument as well - so this would work too:
$("#grpList").DataTable().row.add(resp.data).draw(false);
The issue is on server side.
You define $jsonArray as a string ! That's wrong.
Try this instead:
$jsonArray = []; // An ARRAY here!
if($data->num_rows > 0)
{
while($row = $data->fetch_assoc())
{
array_push($jsonArray, json_encode( // Use array_push here
array(
"dept_name" => $row['department_name'],
"city_name" => $row['city_name'],
"emp_id" => $row['emp_id'],
"emp_name" => $row['name']
));
}
echo json_encode(array("data" => $jsonArray, "status" => 'success'));
}
EDIT
I don't if the above works... Since I did not test it.
But here's how I would have writen it (I guess you'll have more chances with it):
$jsonArray = [];
if($data->num_rows > 0) {
while($row = $data->fetch_assoc()) {
// A temp array to rename the one of the keys...
$tempArray = [];
$tempArray = ["dept_name"] = $row['department_name'];
$tempArray = ["city_name"] = $row['city_name'];
$tempArray = ["emp_id"] = $row['emp_id'];
$tempArray = ["emp_name"] = $row['name'];
// Push to the jsonArray now...
array_push($jsonArray,$tempArray);
}
// And finally the result array... To be json encoded
$result = [];
$result = ["status"] = "success";
$result = ["data"] = jsonArray;
echo json_encode($result);
}
Note that without renaming one key and if there's only 4 data per rows from the DB... You could have done array_push($jsonArray,$row); directly, without using the $tempArray.
So try this... AND then apply Jack's answer. ;)
I used a php variable into Javascript like this-
var Coordinates = <?php echo json_encode($coords); ?>;
And now I want to stringify it so I used
var JSON_Coordinates = JSON.stringify(Coordinates);
the result is
["-98.47442960102632,38.51861967935271","-98.46128420909388,38.17510666712973","-97.91584295178713,38.17274814619617", -"97.91882439611877,38.51683243137235", "-98.47442960102632,38.51861967935271"]
But I want It to be like this-
[[-98.47442960102632,38.51861967935271],[-98.46128420909388,38.17510666712973],[-97.91584295178713,38.17274814619617], [-97.91882439611877,38.51683243137235], [-98.47442960102632,38.51861967935271]]
So how to replace " " with [ ]?
You could fix it on the server side:
$coords = array(
'-98.47442960102632,38.51861967935271',
'-98.46128420909388,38.17510666712973',
'-97.91584295178713,38.17274814619617',
'-97.91882439611877,38.51683243137235',
'-98.47442960102632,38.51861967935271'
);
$coords = array_map(function($coord) {
list($lat, $lon) = explode(",", $coord);
return array((float) $lat, (float) $lon);
}, $coords);
echo json_encode($coords);
Output (pretty printed):
[
[-98.474429601026, 38.518619679353],
[-98.461284209094, 38.17510666713],
[-97.915842951787, 38.172748146196],
[-97.918824396119, 38.516832431372],
[-98.474429601026, 38.518619679353]
]
Before converting to json in php, you could convert each coords string to an array in a loop, then ensure values are not strings but numeric using JSON_NUMERIC_CHECK
<?php
foreach ($coords as &$value) {
$value = explode(',', $value); // prevent to array like ["23","45"]
}
unset($value); // avoid reuse of &reference variable by mistake
echo json_encode($coords, JSON_NUMERIC_CHECK);
?>
I am querying MS SQL Server and storing the results in a json array, then passing the results to Javascript. My issue is that based off if a variable isset the array length SHOULD be either 4 or 5 length. However, the array is ALWAYS showing a length of 5.
This is the php that I am using.
<?php
$sql = "Select ";
if (isset($_GET['namepull'])) {
$sql .= "name,";
}
$sql .= " address, city, state, zip from employeefile";
$db->setQuery($sql);
$rows = $db->loadRowList();
$output = array();
foreach ($rows as $row) {
array_push($output, $row);
}
echo $sql;
$jsondata = json_encode($output[0]);
?>
Which to me the below query strings should show an array length of
4 = Select address, city, state, zip from employeefile
5 = Select name, address, city, state, zip from employeefile
Now the issue that I have is when it hits the below <script> a length of 5 is always produced, regardless of the query. How should I modify the <script> so that an accurate count is returned?
<script>
var arrayfromphp = <?php echo $jsondata; ?>;
alert (arrayfromphp.length);
</script>
If I perform a console.log(arrayfromphp) the last element when the count should be 4 is always undefined x 1
Edit
If I use var_dump below is the output I get (which is what I expect)
Array ( [0] => XXXXXXXXX [1] => New York [2] => New York [3] => 33333 )
Array ( [0] => Jackie [1] => XXXXXXXXX [2] => New York [3] => New York [4] => 33333 )
Edit Again
It appears the issue is stemming from how I am populating a Javascript array from the php array. See edit below with notes above lines
var arrayfromphp = <?php echo $jsondata; ?>;
//Shows accurate count of 4
console.log(arrayfromphp);
var values = [];
if (arrayfromphp.length = 5) {
for (var i = 1; i < arrayfromphp.length; i++) {
values.push(arrayfromphp[i]);
}
} else if (arrayfromphp.length = 4) {
for (var i = 0; i < arrayfromphp.length; i++) {
values.push(arrayfromphp[i]);
}
}
//Shows 5
alert(arrayfromphp.length);
//Shows 5 with undefined x 1
console.log(arrayfromphp);
I'm trying to convert a PHP multidimensional array to a javascript array WITHOUT using json encoder because of the version of the server.
Exemple of a multidimensional Array :
Array (
[0] => Array (
[0] => 18
[1] => Région Grand EST
[2] => GE )
[1] => Array (
[0] => 17
[1] => Région Grand OUEST / NORD
[2] => GO N )
[2] => Array (
[0] => 25
[1] => Région Grand OUEST / SUD
[2] => GO S )
)
Currently for no multidimensional array i'm using this function :
function js_str($s) {
return '"' . addcslashes($s, "\0..\37\"\\") . '"';
}
function js_array($array) {
if (is_array($array)) {
$temp = array_map('js_str', $array);
return '[' . implode(',', $temp) . ']';
}
return '[-1]';
}
But i can't use it for multidimensional, i'm trying to do somthing similar recursively to do it with any size of array.
To get a result like :
myArray = [[18, 'Région Grand EST', 'GE'],[17, 'Grand OUEST / NORD', 'GO N'], [25, 'Région Grand OUEST / SUD', 'GO S']];
It's really hard to find an answer without json_encode, thanks for your help.
(Yes i'm developping on a prehistoric server)
I would approach this problem with a recursive function like this:
function js_array($array) {
if (is_array($array)) {
$temp = array();
$output = '[';
foreach ($array AS $key=>$value) {
$temp[] .= "'$key':" . js_array($value);
}
$output .= implode(',', $temp);
$output .= "]";
} else {
$output .= "'$array'";
}
return $output;
}
What we're doing here is evaluating each element of the array to see if it is also an array. Each level drills down into itself until we are left with simple key:value pairs.
You can edit for special characters or to drop the array keys if you want.
Thx to Danielml01 for his help.
Here the solution used :
function js_array($array) {
if (is_array($array)) {
$temp = array();
$isObject = false;
foreach ($array AS $key=>$value) {
if (is_numeric($key))
$temp[] .= js_array($value);
else {
$isObject = true;
$temp[] .= "'$key':" . js_array($value)."";
}
}
if ($isObject)
$output = "{".implode(',', $temp)."}";
else
$output = "[".implode(',', $temp)."]";
}
else
$output = "'".$array."'";
return $output;
}
I need to create a JSON array starting with index 1
Here is my code which picks the images from the websites
$image_urls = array();
//get all images URLs in the content
foreach($get_content->find('img') as $element)
{
/* check image URL is valid and name isn't blank.gif/blank.png etc..
you can also use other methods to check if image really exist */
if(!preg_match('/blank.(.*)/i', $element->src) && filter_var($element->src, FILTER_VALIDATE_URL))
{
$image_urls[] = $element->src;
}
}
//prepare for JSON
$output = array('title'=>$page_title, 'images'=>$image_urls, 'content'=> $page_body);
echo json_encode($output); //output JSON data
data.images gives the array bu it starts with 0
Try
$output = array();
$output['1'] = array('title'=>$page_title, 'images'=>$image_urls, 'content'=> $page_body);
echo json_encode($output); //output JSON data
Output would be:
{"1":{"title":(*page_title*),"images":(*img_url*),"content":(*page_body*)}}
Try using array_unshift
$image_urls = array_unshift($image_urls,null);//add an element at the zeroth index
unset($image_urls[0]);//remove the zero index
An single line solution to the image_url array:-
$arr=array(1,2,3,4,5,6);
$arr = array_combine(range(1, count($arr)), $arr);
echo '<pre>';print_r($arr);
Output :
Array
(
[1] => 1
[2] => 2
[3] => 3
[4] => 4
[5] => 5
[6] => 6
)