json_encode not working for a nested array - php

I've been trying to return results from 2 queries as json. var_dump($data) works but can't json_encode returns empty/ not working.
$data = array();
$array_articles = array();
$sql_articles = $mysqli->query("select something something");
while ( $article = $sql_articles->fetch_assoc() ){
$array_articles[] = $article;
}
$array_posts = array();
$sql_posts = $mysqli->query("select something something");
while ( $post = $sql_posts->fetch_assoc() ){
$array_posts[] = $post;
}
$data = array(
'top_articles' => $array_articles,
'top_posts' => $array_posts
);
echo json_encode( $data );

All the things you put in json_encode must be UTF8. I think some of the content is not UTF-8 encoded.
You can add extra parameters to json_encode.
You could give it a try like this:
echo json_encode($data, JSON_INVALID_UTF8_IGNORE | JSON_PARTIAL_OUTPUT_ON_ERROR)

Related

How to convert JSON string to arrays

With php, I need to convert json arrays into arrays, what should I do, json_encode didn't work for me, thanks in advance for help.
//json sequence
[
{
"name":"Menu",
"sub":
[
{
"name":"Menu 2",
"url":"menu-2.php"
}
]
}
]
this way i should do
array(
'name' => 'Menu',
'sub' => array(
array(
'name' => 'Menu 2',
'url' => 'menu-2.php'
)
)
)
i am creating json array with this function
Do I have to make a change here? I'm not really good in arrays.
<?php
$connect = new PDO("mysql:host=localhost; dbname=propanel_001", "root", "");
$parent_category_id = "";
$query = "SELECT * FROM tb_sayfalar";
$statement = $connect->prepare($query);
$statement->execute();
$result = $statement->fetchAll();
foreach($result as $row)
{
$data = get_node_data($parent_category_id, $connect);
}
echo json_encode(array_values($data));
function get_node_data($parent_category_id, $connect)
{
$query = "SELECT * FROM tb_sayfalar WHERE parent_id = '".$parent_category_id."'";
$statement = $connect->prepare($query);
$statement->execute();
$result = $statement->fetchAll();
$output = array();
foreach($result as $row)
{
$sub_array = array();
if (array_values(get_node_data($row['id'], $connect))) {
$sub_array['name'] = $row['page_name'];
$sub_array['sub'] = array_values(get_node_data($row['id'], $connect));
}else{
$sub_array['name'] = $row['page_name'];
$sub_array['url'] = $row['page_url'].".php";
}
$output[] = $sub_array;
}
return $output;
}
?>
This is what you need, json_decode($json,true);
<?php
$json = '[{"name":"Menu","sub":[{"name":"Menu 2","url":"menu-2.php"}]}]';
$array = json_decode($json,1);
print_r($array[0]);
?>
DEMO: https://3v4l.org/JZQCn
OR use it as a parsable string representation of a variable with var_export()
<?php
$json = '[{"name":"Menu","sub":[{"name":"Menu 2","url":"menu-2.php"}]}]';
$array = var_export(json_decode($json,1)[0]);
print($array);
?>
DEMO: https://3v4l.org/rLA9R
You must use json_decode to convert JSON representing Object to Associative array.
Example Code
$resArr = json_decode($response, true);
For more information look at PHP JSON_DECODE

encode json array from latin1

So i am very new to php and having problem with my array.
"Basically I have an array with 5 fields.
Now the data is partially in latin1-german. But this let's the php output "null". How do I decode the array, that makes the php return the right text?"
edit:
So I altered the code (JSON_PRETTY_PRINT made it return nothing).
But the problem still remains. The special characters like "ä" and "ü" still make it return ":null".
// get all products from products table
$result = mysql_query("SELECT *FROM silberhell_app") or die(mysql_error());
// check for empty result
if (mysql_num_rows($result) > 0) {
// looping through all results
// products node
$response["products"] = array();
while ($row = mysql_fetch_array($result)) {
// temp user array
$product = array();
$product["pid"] = $row["pid"];
$product["name"] = $row["name"];
$product["kategorie"] = $row["kategorie"];
$product["beschreibung"] = $row["beschreibung"];
$product["bild"] = $row["bild"];
$product["preis"] = $row["preis"];
array_map($product, "utf8_encode"); // encode array values
$products[] = $product; // insert product into array
}
$data = array(
//'success' => 1,
'products' => $products
);
}
echo json_encode($data); // make it slightly more readable
?>
Slightly cleaned up, should work now:
$products = array();
while ($row = mysql_fetch_array($result)) {
$product = array();
$product["pid"] = $row["pid"];
[...]
array_map("utf8_encode", $product); // encode array values
$products[] = $product; // insert product into array
}
$data = array(
'success' => 1,
'products' => $products
);
echo json_encode($data, JSON_PRETTY_PRINT); // make it slightly more readable

'where' like querying an array or object

[{"id":1,"username":"example","email":"example#gmail.com","password":"example123","created_at":"2015-01-13 11:39:24","updated_at":"2015-01-13 11:39:24"},
{"id":2,"username":"ex2","email":"ex#ex.com","password":"example","created_at":"2015-01-13 11:39:02","updated_at":"2015-01-13 11:39:02"}]
I got an object like above. The thing I want to is select the object that's id is 1 for example. Like
select * from object where id=1
with SQL
How to do it?
I hope i got your question right.
Try the following
<?php
$array = json_decode('[{"id":1,"username":"example","email":"example#gmail.com","password":"example123","created_at":"2015-01-13 11:39:24","updated_at":"2015-01-13 11:39:24"},
{"id":2,"username":"ex2","email":"ex#ex.com","password":"example","created_at":"2015-01-13 11:39:02","updated_at":"2015-01-13 11:39:02"}]');
foreach( $array as $v ) {
if( $v["id"] == 1 ) {
echo "I am ID 1";
break;
}
}
Decode your object (http://php.net/manual/it/function.json-decode.php) and then traverse your array with a foreach checking the id value inside of it with an if statement.
$obj_to_array = json_decode($json_object);
$target = '';
foreach($obj_to_array as $row){
if($row['id'] == 1)
$target = $row;
}
// $target holds your row with id = 1
$data = '[{"id":1,"username":"example","email":"example#gmail.com","password":"example123","created_at":"2015-01-13 11:39:24","updated_at":"2015-01-13 11:39:24"},
{"id":2,"username":"ex2","email":"ex#ex.com","password":"example","created_at":"2015-01-13 11:39:02","updated_at":"2015-01-13 11:39:02"}]';
$data = json_decode($data);
$id = 1;
$key = 'id';
$data = array_filter(
$data,
function($value) use ($key, $id) {
return ($value->$key == $id);
}
);
var_dump($data);
Decode the object using json_decode. Use the code below
<?php
$json='[{"id":1,"username":"example","email":"example#gmail.com","password":"example123","created_at":"2015-01-13 11:39:24","updated_at":"2015-01-13 11:39:24"},
{"id":2,"username":"ex2","email":"ex#ex.com","password":"example","created_at":"2015-01-13 11:39:02","updated_at":"2015-01-13 11:39:02"}]';
$p = json_decode($json,true);
$l=count($p);
for($i=0;$i<=$l;$i++){
$id=$p[$i]["id"];
if($id==1){
print_r($p[$i]); // WIll print the id if 1
}
}
Hope this helps you

preg_replace remove [] around array

I currently have an array that looks like this:
[[{"name":"Shirt","data":[1,1,5,5,1,10000]},{"name":"Skittles","data":[1,9,1,1]}]]
I'm using:
preg_replace('/"([^"]+)"\s*:\s*/', '$1:',json_encode($results));
to create an array that should look like this:
[{"name":"Shirt","data":[1,1,5,5,1,10000]},{"name":"Skittles","data":[1,9,1,1]}]
However I can't seem to get rid of the extra set of brackets.
My model:
function get_data()
{
$this->db->select('ItemName, QuantitySold');
$query = $this->db->get('transactions');
$results = array();
foreach ($query->result_array() as $row)
{
if(!isset($results[$row['ItemName']]))
$results[$row['ItemName']] = array('name' => $row['ItemName'], 'data' => array());
$results[$row['ItemName']]['data'][] = $row['QuantitySold'];
}
//Rekey arrays so they aren't associative
$results = array_values($results);
return $results;
}
My controller:
function test()
{
$this->load->model('data');
$series_data[] = $this->data->get_data();
$data['series_data'] = json_encode($series_data, JSON_NUMERIC_CHECK);
preg_replace('/"([^"]+)"\s*:\s*/', '$1:',json_encode($series_data));
$this->load->view('chart', $data);
}
thanks in advance.
Why use preg_replace.... this is simply json encoded data:
$string = '[[{"name":"Shirt","data":[1,1,5,5,1,10000]},{"name":"Skittles","data":[1,9,1,1]}]]';
var_dump(
json_encode(
json_decode($string)[0]
)
);

Add new lines to JSON

I have successfully get content from the database and output the results in JSON. But I want to add a text that doesn't exists in the database and it's here I'm stuck.
$statement = $sql->prepare("SELECT data_filename,
data_filetype,
data_uniqid,
data_description,
data_coordinates,
exif_taken,
exif_camera,
exif_camera_seo,
exif_resolution,
exif_sensitivity,
exif_exposure,
exif_aperture,
exif_focallength,
is_downloadable,
is_notaccurate,
allow_fullsize
FROM photos
WHERE data_filename = 'P1170976'");
$statement->execute();
$results = $statement->fetchAll(PDO::FETCH_ASSOC);
$json = json_encode($results);
echo $json;
That code gives me
[{"data_filename":"P1170976","data_filetype":"JPG","data_uniqid":"","data_description":"","data_coordinates":"","exif_taken":"0000-00-00","exif_camera":"","exif_camera_seo":"","exif_resolution":"","exif_sensitivity":"0","exif_exposure":"","exif_aperture":"","exif_focallength":"","is_downloadable":null,"is_notaccurate":null,"allow_fullsize":null}]
Which is correct of course but if I add these 2 new lines under $json = json_encode... I'm getting null.
$newdata = array('test' => 'just testing');
$json[] = $newdata;
What have I done wrong here?
json_encode() returns a string, so you can’t handle it as an array, i.e. add elements to string.
As noted in comments, you need to add those lines before json_encode() or decode it back to array using json_decode(), then apply the lines and then back json_encode().
Example about usage of json_encode and json_decode:
$array = array("this" => array("will" => array("be" => "json")));
$string = json_encode($array); // string(31) "{"this":{"will":{"be":"json"}}}"
// ...
$array2 = json_decode($string); // now it’s same array as in first $array
$array2["new"] = "element";
$string2 = json_encode($array2);
var_dump($string2); // string(46) "{"this":{"will":{"be":"json"}},"new":"string"}"
Try this:
$newdata = array('test' => 'justtesting');
$results[] = $newdata;
$json = json_encode($results);
or if you definately need it after its encoded:
$json = json_encode($results);
//lots of stuff
$jarray = json_decode($results, true);
$newdata = array('test' => 'justtesting');
$jarray[] = $newdata;
$json = json_encode($jarray);

Categories