Remove Index inside variable - php

I have code like this, but how can I remove "1","2","3" inside "collaterals" ?
{
"brokerPartner": "XX",
"collaterals": {
"1": {
"stockCode": "ABC",
"contractCode": "GE01905438831212",
"qtyEfek": "900"
},
"2": {
"stockCode": "DEF",
"contractCode": "GE01905438831212",
"qtyEfek": "1900"
},
"3": {
"stockCode": "HIJ",
"contractCode": "GE01905438831212",
"qtyEfek": "100"
}
},
"dueDate": "2019-08-06",
"stockType": "S",
"tradeDate": "2019-08-06"
}
I want the following result:
"collaterals":{
{
"stockCode":"ABC",
"contractCode":"GE01905438831212",
"qtyEfek":"900"
},
{
"stockCode":"DEF",
"contractCode":"GE01905438831212",
"qtyEfek":"1900"
},
{
"stockCode":"HIJ",
"contractCode":"GE01905438831212",
"qtyEfek":"100"
}
}
I'm using laravel 5.6

You can't get collaterals as an object since a json object has to be indexed, but you can get an array of objects by creating a numeric array from your associative one:
$data = json_decode($json, true);
$data['collaterals'] = array_values($data['collaterals']);
$json = json_encode($data);
This will result in { "brokerPartner": "XX", "collaterals":[{"stockCode":"ABC", ...}, {"stockCode":"DEF", ...}]} (most of the string ommited).

Related

How to decode this json with foreach

This is the JSON
{
"circuit_list": [
{
"_id": "58c0f378a986f808cdaf94cf",
"aggregation": {
"dev_name": "ME2-D2-BOO",
"port": {
"desc": "AKSES_SITE_SITE-TSEL_ME2-D2-BOO#1/2/5_200M_BOO082#CIPAKUBOO534",
"name": "1/2/5"
}
},
"area": "AREA 2",
"site_id": "N/A",
"site_name": "N/A"
},
{
"_id": "58c0f378a986f808cdaf94d0",
"aggregation": {
"dev_name": "ME2-D2-BOO",
"port": {
"desc": "AKSES_SITE_SITE-TSEL_ME2-D2-BOO#1/2/5_200M_BOO082#CIPAKUBOO534",
"name": "1/2/5"
}
},
"area": "AREA 2",
"site_id": "N/A",
"site_name": "N/A"
}
}
I already try with this code
$json = json_decode($url, true);
foreach($json as $value)
{
$_id = $value->_id;
}
it didn't work. Please help, I need to get the value to show them on the view. Did I do this wrong? this json is difficult because i didn't understand the structure.
I usually decode json with format
[{"id":"1","name":"faisal"}]
like this and with my foreach it's working.
If the second parameter of json_decode is true, the function will return an array instead of an object. Also, you would need to loop over the circuit_list property of the object.
$json = json_decode($url); // <- remove the parameter
foreach($json->circuit_list as $value) // <- loop over circuit_list
{
$_id = $value->_id;
}
<?php
$json = json_decode($url,true);
foreach($json['circuit_list'] as $value)
{
$id = $value['_id'];
}
?>

How to access array inside document using PHP [duplicate]

This question already has answers here:
Get data from JSON file with PHP [duplicate]
(3 answers)
Closed 6 years ago.
I want print specific vars from array inside a document.
JSON structure:
{
"return": {
"string": "2222",
"contacts": [
{
"contact": {
"id": "09890423890"
}
},
{
"contact": {
"id": "2423444"
}
},
{
"contact": {
"id": "24242423"
}
},
etc
]
}
}
I am trying to do this in PHP (and already decoded that json). How can I access and print all ids using foreach or for?
I can not understand how I can manage "return" scope.
You can decode the json contents and use it like an array. This should work:
$json = json_decode($string, true);
$contacts = $json['return']['contacts'];
foreach($contacts as $contact){
echo $contact['contact']['id'];
}
Json decode to array:
$json = json_decode($strjson, true); // decode the JSON into an associative array
and
echo "<pre>";
print_r($json);
And foreach:
foreach ($json as $key => $value) {
echo $key . " ". $value. "<br>";
}
Working example:
$json = '{
"return": {
"string": "2222",
"contacts": [
{
"contact": {
"id": "09890423890"
}
},
{
"contact": {
"id": "2423444"
}
},
{
"contact": {
"id": "24242423"
}
}
]
}
}';
$json = json_decode($json, true);
print_r($json);
foreach ($json['return']['contacts'] as $val) {
echo $val['contact']['id']."<br>";
}
Try this code:
$json ='
{
"return": {
"string": "2222",
"contacts": [
{
"contact": {
"id": "09890423890"
}
},
{
"contact": {
"id": "2423444"
}
},
{
"contact": {
"id": "24242423"
}
},
etc
]
}
}
';
$array = json_decode($json,TRUE);
foreach($array['return']['contacts'] as $value ){
echo $value['id'];
}
Use file_get_contents function if you want to pull data from file.

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() .'}}';
}
}

How to place the json objects into array usin 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.

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

Categories