function array_push returns empty array [duplicate] - php

This question already has an answer here:
PHP json_encode returns null value from unicode character
(1 answer)
Closed 7 years ago.
I try to save the rows of a table in an array but I am getting an empty array.
My code is:
$a = array();
$b = array();
if ($result->num_rows > 0){
while ($row = $result->fetch_assoc()) {
$b["id"] = $row["id"];
$b["title"] = $row["title"];
$b["description"] = $row["description"];
$b["lat"] = $row["lat"];
$b["lng"] = $row["lng"];
$b["walkId"] = $row["walkId"];
echo json_encode($b);
array_push($a,$b);
}
echo json_encode($a);
}
Using echo json_encode($b); I see the results one by one but the array a is empty.
EDIT 1
After Random's help, using the echo print_r($a,true); I am getting the below screenshot:
And the screenshot from other tables in which I get the data correctly is:
EDIT 2
problem with json_encode. I get the below
[{"id":"55","title":"\u00ce\u203a\u00ce\u00bf\u00cf\u2026\u00ce\u00bb\u00ce\u00bf\u00cf\u2026\u00ce\u00b4\u00ce\u00ac\u00ce\u00b4\u00ce\u00b9\u00ce\u00ba\u00ce\u00b1","description":"\u00ce\u201c\u00ce\u00b5\u00ce\u00bd\u00ce\u00b9\u00ce\u00ba\u00ce\u00ae \u00ce\u00b1\u00ce\u00bd\u00ce\u00b1\u00cf\u2020\u00ce\u00bf\u00cf\u0081\u00ce\u00ac \u00cf\u0192\u00cf\u201e\u00ce\u00b1 x\u00ce\u00b1\u00cf\u0081\u00ce\u00b1\u00ce\u00ba\u00cf\u201e\u00ce\u00b7\u00cf\u0081\u00ce\u00b9\u00cf\u0192\u00cf\u201e\u00ce\u00b9\u00ce\u00ba\u00ce\u00ac \u00cf\u201e\u00ce\u00b7\u00cf\u201a \u00ce\u00b3\u00ce\u00b1\u00cf\u0192\u00cf\u201e\u00cf\u0081\u00ce\u00bf\u00ce\u00bd\u00ce\u00bf\u00ce\u00bc\u00ce\u00af\u00ce\u00b1\u00cf\u201a \u00cf\u201e\u00ce\u00b7\u00cf","lat":"40.634356","lng":"22.940716","walkId":"92"},{"id":"56","title":"\u00ce\u2018\u00ce\u00b3\u00ce\u00bf\u00cf\u0081\u00ce\u00ac \u00ce\u0153\u00ce\u00bf\u00ce\u00b4\u00ce\u00b9\u00ce\u00ac\u00ce\u00bd\u00ce\u00bf","description":"H \u00ce\u00b9\u00cf\u0192\u00cf\u201e\u00ce\u00bf\u00cf\u0081\u00ce\u00af\u00ce\u00b1 \u00ce\u00bc\u00ce\u00b9\u00ce\u00b1\u00cf\u201a \u00ce\u00b9\u00cf\u0192\u00cf\u201e\u00ce\u00bf\u00cf\u0081\u00ce\u00b9\u00ce\u00ba\u00ce\u00ae\u00cf\u201a \u00ce\u00b1\u00ce\u00b3\u00ce\u00bf\u00cf\u0081\u00ce\u00ac\u00cf\u201a. \u00cf\u201e\u00ce\u00b1 X\u00ce\u00b1\u00cf\u0081\u00ce\u00b1\u00ce\u00ba\u00cf\u201e\u00ce\u00b7\u00cf\u0081\u00ce\u00b9\u00cf\u0192\u00cf\u201e\u00ce\u00b9\u00ce\u00ba\u00ce\u00ac \u00cf\u201e\u00ce\u00b7\u00cf\u201a \u00ce","lat":"40.634609","lng":"22.941081","walkId":"92"}

First thing I note is the special ? that appears 3 time. The problem must come from here.
Try to edit the 3 descriptions that contain the special ? so it doesn't appear again in the print_r.
That must turn array_push into an error.
You could also try to encode it in latin to make it safe. (please follow #deceze link to understand what to do)

Related

How to dynamically insert JSON data into a PHP array for foreach [duplicate]

This question already has answers here:
How to create a JSON object
(5 answers)
Closed 3 years ago.
I have the following PHP code, which gets executed when I hit the Submit button in a form:
// Save data
if(isset($_POST['save'])){
$newDataArr = array();
foreach ($data_array[0] as $k=>$v){
$newDataArr[] = array($k => $_POST[$k]);
}// ./ foreach
echo json_encode($newDataArr);
}
The echo I get is the following:
[{"ID->id":"esKZSCDfIC"},{"DT->createdAt":"2020-01-26T13:02:42"},{"DT->updatedAt":"2020-01-26T13:02:42"},{"ST->aString":"hey1"},{"NU->number":123},{"GPS->coords":["2.2222","44.4444"]},{"BL->aBool":false},{"AR->theArray":["xx","ww"]},{"FL->theFile":"https:\/\/xscoder.com\/xserver\/uploads\/6dydDtoTt5JjZzFc5L5V_image.jpg"},{"PO->userPointer":"vbN3b0C7bC"}]
Then I'll have to add that array into my JSON file as it follows:
$data = json_encode(array_values($newDataArr), JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
file_put_contents('Test.json', $data);
But of course the syntax of my $newDataArr is not the right one, each JSON object must not be inside the { }, so this:
{"ID->id":"esKZSCDfIC"},
must become:
"ID->id":"esKZSCDfIC",
Is there a way to dynamically create a valid JSON array and push it to my Test.json file?
I've been through many posts on StackOverflow, but the result I get is always the same. I must use the PHP code above to get keys and values from my HTML inputs.
Instead of creating and pushing a new array on each iteration, set the values this way:
$newDataArr[$k] = $_POST[$k];
Hope this helps.

How to remove double quotes from json_encode in php? [duplicate]

This question already has answers here:
Remove double quote in json_encode()
(6 answers)
Closed 3 years ago.
code:
<?php
if(!isset($candidate_id))
{
header("location:".base_url()."login");
}
$this->db->select('event,event_title,description,s_date');
$this->db->from('event');
$this->db->where('candidate_id',$cid);
$this->db->order_by('s_date','desc');
$query = $this->db->get();
if($query->num_rows() > 0)
{
$result = $query->result_array();
$record = array();
foreach($result as $row)
{
$record[] = $row;
}
echo json_encode($record,JSON_NUMERIC_CHECK);
}
else
{
$this->session->set_flashdata('no_event',"<p>No event Added</p>");
}
?>
current output:
[{"event":"2019-03-06","event_title":"meeting","description":"meeting with xyz","s_date":"2019-03-04"}]
expected output:
[{event:"2019-03-06",event_title:"meeting",description:"meeting with xyz",s_date:"2019-03-04"}]
I am creating a simple JSON API using json_encode() function. Now, API I created successfully but the output is unexpected as I mention above. Now, What I actually want I also mention above. So, How can get I expected output? Please help me.
Thank You
The problem is, if you remove the quotes from the key, it's no longer JSON. I'm assuming you want it similar to a JavaScript object, but that should be done on the client side, using JSON.parse().
ie:
var apiResponse = '[{"event":"2019-03-06","event_title":"meeting","description":"meeting with xyz","s_date":"2019-03-04"}]';
var json = JSON.parse(apiResponse);
console.log(json);
console.log(json[0].description);
Try this
$array_final = preg_replace('/"([a-zA-Z_]+[a-zA-Z0-9_]*)":/','$1:',json_encode($you-array));
Output
{event:"2019-03-06",event_title:"meeting",description:"meeting with xyz",s_date:"2019-03-04"}

how to get value from array [duplicate]

This question already has an answer here:
How to extract and access data from JSON with PHP?
(1 answer)
Closed 4 years ago.
how to get value from array in php from api
here is my code
$data = callBitAPI('GET','https://min-api.cryptocompare.com/data/pricemultifull?fsyms='.strtoupper($bc->slug).'&tsyms=USD');
if(!empty($data)){
$data = json_decode($data,true);
// echo '<pre>';
// print_r($data);
$data = getRelevantCryptoArray($data,$bc->slug);
}
and here is my result
Please see Attachment
http://prntscr.com/k7hawi
Um... simply
$price = $data['RAW']['BTC']['USD']['PRICE'];
print_r($price);
unless I'm missing something?
dd($data['RAW']['BTC']['USD']['PRICE']) and see the result

Array to string conversion in......array [duplicate]

This question already has answers here:
Display array values in PHP
(9 answers)
Closed 7 months ago.
I want to get the average of a column in a table,
table: buy
column: c1
when I called the database
with this:
$query="Select AVG(c1) as average FROM buy";
$result_array=mysql_query($query);
$line = mysql_fetch_array($result_array);
and when I called with php like this
<?php echo $line; ?>
it came up error with this message
Array to string conversion in .......... on line 50
Array
what did I do wrong? I think because I treated arrays as a string. but how can i fix this?
Please take a look that $line returns an array. So, you can't echo an array. One thing you can do is
echo "<pre>";
print_r($line);
Check what the array looks like.
Is it a single row that's been returned? In that case you can write
echo $line['average'];
If it's more than one row:
while ($line = mysql_fetch_array($result_array)) {
echo $line['average'];
}
Hope this helps.
Peace! xD

How to properly deserialize a string from JQuery using PHP? [duplicate]

This question already has answers here:
JQuery string not parsing correctly in PHP
(2 answers)
Closed 9 years ago.
I was wondering, does anyone know how do I properly deserialize a string from a JQuery using PHP? The string that JQuery passes into my PHP file is this:
age_gender=1&age_gender=2&age_gender=3&age_gender=4&age_gender=5&age_gender=6
The values I need are the numbers after the equal signs (they are just dummy values that I used for testing).
EDIT: Actually, I am already using parse_str(). Here is my PHP code:
if(isset($_POST['age_gender'])) {
$formSerialized = $_POST['age_gender'];
$formData = array();
parse_str($formSerialized, $formData);
addRow($formData, $link);
}
function addRow($dataArray, $link) {
$age_group = $dataArray[0];
$populations = array(intval($dataArray[1]) + intval($dataArray[2]), intval($dataArray[1]), intval($dataArray[2]));
$percents = array(doubleval($dataArray[3]) + doubleval($dataArray[4]), doubleval($dataArray[3]), doubleval($dataArray[4]));
$m_per_100_f = doubleval($dataArray[6]);
$query = "INSERT INTO national_age_gender_demographics (age_group, both_pop, male_pop, female_pop, both_percent, male_percent, female_percent, males_per_100_females)
VALUES ('$age_group','$populations[0]','$populations[1]','$populations[2]','$percents[0]','$percents[1]','$percents[2]','$m_per_100_f')";
$result = mysqli_query($link,$query);
if(!$result) die( "Query: " . $query . "\nError:" . mysql_error() );
}
For some reason, I am getting a blank string for $age_group, and 0's for all other values. Could anyone help me here?
See parse_str()
Example:
parse_str('age_gender=1&age_gender=2&age_gender=3&age_gender=4&age_gender=5&age_gender=6', $output);
print_r($output);
Also if you want to get the querystring of the request you can get it with php using $_SERVER['QUERY_STRING']
parse_str()
is the function you are looking for.
You have two options to use with this:
parse_str($string) - this will actually create a variable for each key in the string.
parse_str($string,$arr) - this will populate $arr with an associative array containing all the key=>value pairs from the string.
The documentation gives some great code to demonstrate this behavior:
$str = "first=value&arr[]=foo+bar&arr[]=baz";
parse_str($str);
echo $first; // value
echo $arr[0]; // foo bar
echo $arr[1]; // baz
parse_str($str, $output);
echo $output['first']; // value
echo $output['arr'][0]; // foo bar
echo $output['arr'][1]; // baz

Categories