How to place the json objects into array usin php? - php

this is my php code, to obtain json format data
if($status==1)
{
$post_id=$json_object['post_id'];
$get_postid=mysqli_query($con,"select * from User_Post where post_id='$post_id'");
if(mysqli_num_rows($get_postid)==0)
{
//For failure status if session id is wrong.
http_response_code(500);
echo json_encode(array("error_code"=>"500","error_message"=>"Sorry, post id does not exists."));
}
else
{
foreach($field_check as $values)
{
if($values=='id')
{
$row_array = array();
while ($row = $get_postid->fetch_array())
{
$row_array['id']=$row['post_id'];
$row_array['image_urls']=explode(',',$row['post_image_url']);
$storetag= explode(',',$row['Post_tagged_id']);
$has_liked="false";
$has_commented="false";
}
}
elseif($values=='tagged_users')
{
while ($row = $get_postid->fetch_array())
{
$storetag= explode(',',$row['Post_tagged_id']);
$has_liked="false";
$has_commented="false";
}
for($i=0;$i<count($storetag);$i++)
{
$user=mysqli_query($con,"select user_id, profile_image_url from Wheel_User where user_id='$storetag[$i]'");
if(mysqli_num_rows($user)==0)
{
//For failure status if session id is wrong.
http_response_code(500);
echo json_encode(array("error_code"=>"500","error_message"=>"Sorry, post id does not exists.".die()));
}
else
{
while ($row = $user->fetch_array())
{
$tagged_users[$i]['user_id']=$row['user_id'];
$array['user_id']=$tagged_users[$i]['user_id'];
$pro_image_url[$i]=$row['profile_image_url'];
$short_image_url[$i]=str_replace('_b','_t',$pro_image_url[$i]);
$short_image_url[$i]=str_replace('/images/','/thumbnails/',$short_image_url[$i]);
$array['short_image_url']=$short_image_url[$i];
}
}
array_push($row_array,$array);
}
}
}
array_push($json_response,$row_array);
echo str_replace('\/','/',json_encode($json_response));
}
}
It is returning the following objects
[
{
"id": "1111",
"image_urls": [
"https://docs.google.com/document/d/14kVqw9d2kzYIEClN-SVp2Co2mlglM9F-8HIy0ggTZ3g/edit",
"http://stackoverflow.com/questions/21762150/how-do-i-insert-data-from-a-json-array-into-mysql-database",
"https://drive.google.com/?authuser=0#my-drive",
"https://drive.google.com/?tab=mo&authuser=0#shared-with-me"
],
"0": {
"user_id": "111",
"short_image_url": "chrome://restclient/content/thumbnails/restclient_t.jpg"
},
"1": {
"user_id": "321",
"short_image_url": "chrome://restclient/thumbnails/restclient_t.jpg"
},
"2": {
"user_id": "1234",
"short_image_url": "http://54.169.40.195/wheel/wheel/service/testing/chetan/audio/c71dfe45421b2864476a0bde257f0a57e72084783ce859e26595599670904907.mp3"
}
}
]
but i want to assign name to that array like this
[
{
"id": "1111",
"image_urls": [
"https://docs.google.com/document/d/14kVqw9d2kzYIEClN-SVp2Co2mlglM9F-8HIy0ggTZ3g/edit",
"http://stackoverflow.com/questions/21762150/how-do-i-insert-data-from-a-json-array-into-mysql-database",
"https://drive.google.com/?authuser=0#my-drive",
"https://drive.google.com/?tab=mo&authuser=0#shared-with-me"
],
"tagged_users":[
"0": {
"user_id": "111",
"short_image_url": "chrome://restclient/content/thumbnails/restclient_t.jpg"
},
"1": {
"user_id": "321",
"short_image_url": "chrome://restclient/thumbnails/restclient_t.jpg"
},
"2": {
"user_id": "1234",
"short_image_url": "http://54.169.40.195/wheel/wheel/service/testing/chetan/audio/c71dfe45421b2864476a0bde257f0a57e72084783ce859e26595599670904907.mp3"
}
]
}
i don't know where i have to add this array name. Please help me solve this.
I can't assign the array name like this because $row_array also contains other data
echo str_replace('\/','/',json_encode(array("tagged_user"=>$json_response));

On second to last line this should be what you wanted:
array_push($json_response,array("tagged_users" => $row_array));
Edited to remove second part.

Try with -
array_push($row_array['tagged_users'],$array);
Or define it like -
$row_array['tagged_users'] = array();
Then all the values will be as you want.

Related

How to display info on double array JSON (php)

I would like to know how to display the information below.
Link (JSON):
https://my.callofduty.com/api/papi-client/ce/v1/title/bo4/platform/psn/match/11337378706913618925/matchMapEvents
What I wish to have:
"teams": [
[
{
"provider": "psn",
"username": "Germania1992"
},
{
"provider": "psn",
"username": "killzoneprofi"
},
{
"provider": "psn",
"username": "ayozetf87"
},
{
"provider": "psn",
"username": "Seith911"
},
{
"provider": "psn",
"username": "domibreu92"
}
],
[
{
"provider": "psn",
"username": "Thejuankarboy"
},
{
"provider": "psn",
"username": "Gamermad101"
},
{
"provider": "psn",
"username": "Izdrap"
},
{
"provider": "psn",
"username": "Guerra_sv"
},
{
"provider": "psn",
"username": "TriX_FollOoW_YT"
}
]
],
I want to display the nicks of the different teams
Example: Team 1 = Germania1992, killzoneprofi, ayozetf87, Seith911,
domibreu92
Thanks
You will have to do a double foreach that for sure.
<?php
// Get the json of the team
$team = team("https://my.callofduty.com/api/papi-client/ce/v1/title/bo4/platform/psn/match/11337378706913618925/matchMapEvents");
// Display the teams info
foreach($team as $nb=>$data){
echo "Team $nb<br />";
foreach($data as $key=>$value){
echo "Provider: ".$value->provider."<br />";
echo "Username: ".$value->username."<br />";
}
echo "<hr>";
}
// Returns the team array of the json
function team($jsonURL){
$content=file_get_contents($jsonURL);
$data=json_decode($content);
return $data->data->teams;
}
?>
You could increment the team number by 1 to avoid the first being 0
The above will display the below screenshot (You can format the output as you please)
$result = [];
$counter = 0;
dump($array = json_decode(file_get_contents('https://my.callofduty.com/api/papi-client/ce/v1/title/bo4/platform/psn/match/11337378706913618925/matchMapEvents')));
dump($t = array_column((array)$array, 'teams'));
foreach ($t as $r) {
foreach ($r as $p) {
$counter++;
foreach ($p as $value){
$result["team$counter"][] = $value->username;
}
}
}
var_dump($result);

How to split and change the json format

I am using slimphp v2 and I have the following function
function gt($user) {
$sql = "select id, id as categoryId, mobile, task from actions where status=0";
try {
$db = newDB($user);
$stmt = $db - > prepare($sql);
$stmt - > execute();
$gs = $stmt - > fetchAll(PDO::FETCH_OBJ);
if ($gs) {
$db = null;
echo json_encode($gs, JSON_UNESCAPED_UNICODE);
} else {
echo "Not Found";
}
} catch (PDOException $e) {
echo '{"error":{"text":'.$e - > getMessage().
'}}';
}
}
The default json output looks like:
[{
"id": "1",
"categoryId": "1",
"mobile": "111",
"task": "test"
},
{
"id": "2",
"categoryId": "2",
"mobile": "222",
"task": "test2"
}]
and the output that i am trying to make. I need to generate an ID: 1_(id) then format it like this
[{
id: "1",
task: "test",
}, {
ID: "1_1", //generate this, add 1_id
categoryId: "1",
mobile: "00000",
}, {
id: "2",
task: "test2",
}, {
ID: "1_2", //generate this, add 1_id
categoryId: "2",
mobile: "11111"
}];
Is it possible?
Thanks
I'm not sure if this is exactly what your after but you can gain the desired JSON output by converting your original JSON into an associative array and then restructure the data on each iteration using a Foreach() loop into a new assoc array. After that, you can just convert it back to JSON using json_encode().
Code:
$json = '[{
"id": "1",
"categoryId": "1",
"mobile": "111",
"task": "test"
},
{
"id": "2",
"categoryId": "2",
"mobile": "222",
"task": "test2"
}]';
$jsonArr = json_decode($json, TRUE);
$newArr = [];
foreach ($jsonArr as $v) {
$newArr[] = ['id:'=>$v['id'], 'task:' => $v['task']];
$newArr[] = ['ID:'=>'1_' . $v['id'], 'categoryId' => $v['categoryId'], 'mobile'=>$v['mobile']];
}
$newJson = json_encode($newArr);
var_dump($newJson);
Output:
[{
"id:": "1",
"task:": "test"
}, {
"ID:": "1_1",
"categoryId": "1",
"mobile": "111"
}, {
"id:": "2",
"task:": "test2"
}, {
"ID:": "1_2",
"categoryId": "2",
"mobile": "222"
}]
Edit -- Updated Answer
As discussed in comments, your outputting your SQL array as an object. I've set the Fetch to output as an associative array using PDO::FETCH_ASSOC and changed the foreach() loop to reference the assoc array $gs. This should work but if not then output your results for $gs again using var_dump($gs). You will still need to encode to JSON if needed but this line has been commented out.
function gt($user) {
$sql = "select id, id as categoryId, mobile, task from actions where status=0";
try {
$db = newDB($user);
$stmt = $db->prepare($sql);
$stmt->execute();
$gs = $stmt->fetchAll(PDO::FETCH_ASSOC); //Fetch as Associative Array
if ($gs) {
$db = null;
$newArr = [];
foreach ($gs as $v) { //$gs Array should still work with foreach loop
$newArr[] = ['id:'=>$v['id'], 'task:' => $v['task']];
$newArr[] = ['ID:'=>'1_' . $v['id'], 'categoryId' => $v['categoryId'], 'mobile'=>$v['mobile']];
}
//$newJson = json_encode($newArr); //JSON encode here if you want it converted to JSON.
} else {
echo "Not Found";
}
} catch(PDOException $e) {
//error_log($e->getMessage(), 3, '/var/tmp/php.log');
echo '{"error":{"text":'. $e->getMessage() .'}}';
}
}

search for duplicate classid in json array

I'm trying to search for duplicate classids in a json array and for each duplicate found, echo the dulicate id... This is just an example of the json file.
I've tried a few things but failed - if I posted my code it wouldn't work with this sample code. It's a lot more complex as after I am check another json file for matching ids... and a bunch of other stuff.
Thanks in advance.
{
"response": {
"received": [
{
"items": [
{
"classid": "356464564",
},
{
"classid": "456456456",
},
{
"classid": "356464564",
},
{
"classid": "721248158",
}
]
,
"time_created": 1440782791,
},
{
"items": [
{
"classid": "845362344",
},
{
"classid": "2543634754",
},
{
"classid": "2543634754",
},
{
"classid": "5967856788",
}
]
,
"time_created": 1440456791,
}
}
}
This can do what you're looking for:
<?php
$array = json_decode('{
"response": {
"received": [
{
"items": [
{
"classid": "356464564"
},
{
"classid": "456456456"
},
{
"classid": "356464564"
},
{
"classid": "721248158"
}
]
,
"time_created": 1440782791
}
]
}
}', true);
$cleanArray = array();
foreach($array['response']['received'][0]['items'] as $classid)
{
if(in_array($classid['classid'], $cleanArray))
echo "Duplicate found: ".$classid['classid'].'<br>';
else
$cleanArray[] = $classid['classid'];
}
?>
Try this, it makes the array smaller as matches are found, thus making the algorithm more efficient.
$arr = json_decode($json , true);
$items_array = array_column($arr['response']['items'], 'classid');
foreach ($items_array as $k => $val) {
foreach ($items_array as $k2 => $val2) {
if ($k2 != $k) {
if ($val == $val2) {
unset($items_array[$k]);
if (isset($final[$val])) {
$final[$val]++;
} else {
$final[$val] = 1;
}
}
}
}
}
var_dump($final); //will show you your duplicates

Replace array keys

i have an array like this JSON Example .I'm trying to replace the numeric key ..."conn":{"1":{"... with string key such as "node".
FOR EXAMPLE i want to create this:
{
"Level": [
{
"main": "472321514",
"main_lat": "39.1057579",
"main_lon": "26.5451331",
"conn": {
"node": {
"id": "599416249",
"coords": {
"lat": "39.1055889",
"lon": "26.5452403"
},
"distance": 0.0209442235276
},...
Before json encoding my script is:
foreach ($ways as $w){
$nd=$w->nd;
foreach ($nd as $w2){
$nodes_Array[]=(string)$w2->attributes()->ref;
}
for($ww=0;$ww<count($nodes_Array);$ww++){
$nodes_Array2[$bb]['main'] = $nodes_Array[$ww];
for($gg=0;$gg<count($node_content);$gg++){
if($node_content[$gg]['id']==$nodes_Array2[$bb]['main']){
$nodes_Array2[$bb]['main_lat']= $node_content[$gg]['lat'];
$nodes_Array2[$bb]['main_lon']= $node_content[$gg]['lon'];
}
}
$nodes_Array2[$bb]['conn'] = array_diff($nodes_Array, array($nodes_Array[$ww]));
for($cc=0;$cc<count($nodes_Array2[$bb]['conn']);$cc++){
for($gg=0;$gg<count($node_content);$gg++){
if($node_content[$gg]['id']==$nodes_Array2[$bb]['conn'][$cc]){
$nodes_Array2[$bb]['conn'][$cc]=Array(
'id'=>$node_content[$gg]['id'],
'coords'=>Array(
'lat'=>$node_content[$gg]['lat'],
'lon'=>$node_content[$gg]['lon'],
),
'distance'=>distance($nodes_Array2[$bb]['main_lat'],$nodes_Array2[$bb]['main_lon'],$node_content[$gg]['lat'],$node_content[$gg]['lon'],"K"),
);
}
}
}
$bb++;
}
unset($nodes_Array);
}

PHP Array to JSON

I'm trying to build a JSON object from a mysql query. The JSON structure that I'm striving for should look like this:
{
"a": [
{
"user": "alb",
"time": "2011-09-12 05:56:36"
},
{
"user": "arg",
"time": "2011-09-12 05:56:36"
}
]
"b": [
{
"user": "blah",
"time": "2011-09-12 05:56:36"
},
{
"user": "bleh",
"time": "2011-09-12 05:56:36"
}
]
}
However, my code always returns a JSON object wrapped in an array like so:
[
{
"a": [
{
"user": "alb",
"time": "2011-09-12 05:56:36"
},
{
"user": "arg",
"time": "2011-09-12 05:56:36"
}
]
"b": [
{
"user": "blah",
"time": "2011-09-12 05:56:36"
},
{
"user": "bleh",
"time": "2011-09-12 05:56:36"
}
]
}
]
Here is the php code I'm using:
<?php
$json_data = array();
foreach($blogs as $blog)
{
$sql = "SELECT * from users";
$query = mysql_query($sql);
$ablog = array();
while ($row = mysql_fetch_assoc($query))
{
$json_element = array(
"user"=> $row[username] ,
"time"=> $row[time]
);
array_push($ablog,$json_element);
}
$eblog = array($blog => $ablog);
array_push($json_data,$eblog);
}
$json_output = json_encode($json_data);
print $json_output;
?>
I was wondering: Why am I getting a JSON object wrapped in an array? What am I doing incorrectly in the code above?
Thank you.
The following two lines are creating one-element associative arrays and appending the one-element array to your larger $json_data array:
$eblog = array($blog => $ablog);
array_push($json_data,$eblog);
Instead, just add a new key/value pair to your original array:
$json_data[$blog] = $ablog;

Categories