Creating a JSON array starting with index 1 - javascript

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
)

Related

How to parse a JSON data that has been received by a PHP scipt

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. ;)

PHP Array Length always 5

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);

How to get Session value which is an array in JavaScript?

I have a session set in a php page which stores an array as follows:
firstpage.php
$_SESSION["Counts"]=$some_array;
echo print_r($_SESSION["Counts"]);
Output:
Array ( [Finance] => Array ( [0] => 0 [1] => 3 [2] => 0 [3] => 0 [4] => 1 )
[Human resources] => Array ( [0] => 1 [1] => 5 [2] => 1 [3] => 0 [4] => 0 )
[Infrastructure] => Array ( [0] => 0 [1] => 3 [2] => 1 [3] => 0 [4] => 0 ) ) 1
Retrieving the session data in .js page
SecondJSpage.js
<script type="text/javascript">
var sessionValue= new Array();
var s= new Array();
var s1= new Array();
sessionValue = '<?php $_SESSION["Counts"]; ?>';
document.write(sessionValue); //Does not output anything
for( s1 in sessionValue) {
for( s in s1) {
document.write(s); //Does not output anything
document.write("<br />");
}}
</script>
Only arrays are not being retrieved. A simple session variable is getting displayed. How to solve this problem?
change this line up a little bit..
sessionValue = <?php echo json_encode($_SESSION["Counts"]); ?>;
Use json_encode() for this purpose (Javascript can handle JSON).
Check the manual: http://php.net/json_encode
You cannot echo an array.
<?php echo $_SESSION["Counts"]; // this is an array ?>
And you can't execute PHP within a .js file either (trying to parse PHP within SecondJSpage.js)

JSON Array parsing in PHP and updating in the database

Though this is a textbook problem, but I'm not able to parse from json object. I have a json object coming from a page, and I need to extract the ID,fieldText value so that I can update the table.
Here is how I'm capturing the json and converting it into array, not sure how to extract the values.
if(isset($_POST['postData'])){
$json = json_decode($_POST['postData'],true);
foreach ($json as $key => $value)
{
print_r($key);
//print_r($value);
foreach ($value as $k => $val)
{
//echo "$k | $val <br />";
} }
I need to update the table with [ID] and [fieldText] :
Result should like this::(1:Hello World), (2:The rising Star),(3: Terminator)
My JSON object is like this:
Array(
[fieldName] => Array
(
[0] => fieldText[1]
[1] => fieldText[2]
[2] => fieldText[3]
)
[fieldText] => Array
(
[0] => HelloWorld
[1] => The rising Star
[2] => Terminator
)
[ID] => Array
(
[0] => 1
[1] => 2
[2] => 3
))
Hi it seems that there are three arrays in your JSON, I think it would be better to change the way you generate the JSON to make it simple to understand.
// assumes $arr as the $_POST['postData'] in your case
$arr = array("1"=>"Hello World", "2"=>"The Rising Star", "3"=>"Terminator");
$j = json_encode($arr);
$json = json_decode($j,true);
foreach ($json as $key => $value)
{
echo '('.$key.','. $value.')';
}
The results are :
(1,Hello World)(2,The Rising Star)(3,Terminator)
Hope this can help you.
Hope you can do something like this.
$jsonData = Array(
'Name' => Array
(
0 => 'Text1',
1 => 'Text2',
2 => 'Text3'
),
'Value' => Array
(
0 => 'HelloWorld',
1 => 'The rising Star',
2 => 'Terminator'
),
'ID' => Array
(
0 => 1,
1 => 2,
2 => 3
)
);
$length = count($jsonData['ID']);
for($j=0;$j<$length;$j++) {
echo "(".$jsonData['ID'][$j].": ".$jsonData['Value'][$j].")<br/>";
}
In my opinion you should make your life easier by modifying the json array you receive with $_POST['data'];. If I were in your shoes my json would've been exactly as you need it:
{ 1:'Hello World', 2:'The rising Star',3:'Terminator' }
But if you are not able to change it for any reason I think you could use something like this (basing this example on your code):
$jsonData = json_encode($_POST['json'], true);
$id = $jsonData['ID'];
$fieldText = $jsonData['fieldText'];
$arr = array();
for ($i=0; $i < count($id); $i++) {
$arr[(int) $id[$i]] = $fieldText[$i];
}
var_dump($arr);
Hope this helps you!

Create and edit file javascript with "file_put_contents"?

i would like to create a file.js with php but i think that in my code there are a lot of errors:
i have multidimensional array:
$report= array();
$report= array(array(3,6),array(4,8));
that is:
Array
(
[0] => Array
(
[0] => 3
[1] => 6
)
[1] => Array
(
[0] => 4
[1] => 8
)
)
Set a content-type for js file
$header = "Content-type: text/javascript";
$dir = "outreport/";
$nomefile = "report.js";
//delete a file with same name if exists
foreach (glob($dir."*".$nomefile) as $v){
unlink($v);
}
$percorso = $dir.$nomefile;
file_put_contents($percorso, $report);
header($header);
print($report);
There are two problems:
1) when launching the file.php asks me to download the same file but in javascript
2) in the "outvulcani" it creates the file report.js but is empty
I wish that in the file "report.js" there is the array $report but
written in javascript code:
var reports = [
[3,6]
[4,8]
];
Kindly, you can help me out?
Thanks a lot!
Sorry for my english
PHP has an function to convert Arrays to JSON. You could use this code for "inspiration".
$report = array(array(3,6),array(4,8));
$javascriptContent = json_encode($report);
// Convert to string
$javascriptContent = "var reports = ". $javascriptContent . ";\n";
file_put_contents($percorso, $javascriptContent);
The reason for "Download" is the header, please remove it.

Categories

Resources