How to remove "\" element while add hyperlink in an array? [duplicate] - php

This question already has answers here:
Why is json_encode adding backslashes?
(7 answers)
Closed 4 years ago.
code:
$hyperlink = str_replace("%2F","","http://localhost/android/images/");
if($num>0)
{
$products_arr=array();
$products_arr["data"]=array();
while ($row = $stmt->fetch(PDO::FETCH_ASSOC))
{
extract($row);
$product_item=array(
"image_name" => $image_name,
"image_url" => $hyperlink.$file_s
);
array_push($products_arr["data"], $product_item);
}
echo json_encode($products_arr);
}
I have create a json file using php now I want to add hyperlink inside an array function. I am using str_replace("%2F","","http://localhost/android/images/"); but its not working and json file look like as mention below:
{
"data": [
{
"image_name": "cap-1",
"image_url": "http:\/\/localhost\/android\/images\/Cap-01.png"
},
{
"image_name": "cap-2",
"image_url": "http:\/\/localhost\/android\/images\/Cap-02.png"
},
{
"image_name": "cap-3",
"image_url": "http:\/\/localhost\/android\/images\/Cap-03.png"
},
{
"image_name": "ear-1",
"image_url": "http:\/\/localhost\/android\/images\/Ears-01.png"
},
{
"image_name": "ear-2",
"image_url": "http:\/\/localhost\/android\/images\/Ears-02.png"
},
{
"image_name": "ear-3",
"image_url": "http:\/\/localhost\/android\/images\/Ears-03.png"
},
{
"image_name": "hair-1",
"image_url": "http:\/\/localhost\/android\/images\/Hair Color-01.png"
},
{
"image_name": "hair-2",
"image_url": "http:\/\/localhost\/android\/images\/Hair Color-02.png"
}
]
}
So how can I remove "\" element from url? Please help me.
Thank You

Calling the option JSON_UNESCAPED_SLASHES within json_encode will fix your issue.
$example = json_encode($array, JSON_UNESCAPED_UNICODE |
JSON_UNESCAPED_SLASHES | JSON_NUMERIC_CHECK);

Related

How do I handle this Nested JSON in PHP as below? [duplicate]

This question already has an answer here:
How to extract and access data from JSON with PHP?
(1 answer)
Closed 10 months ago.
I've a GET request in PHP that receives data in JSON as below.
{
"data": {
"id": "1cc58ad2-ccfd-4ede-a6a6-35809c81cb8a",
"type": "payment",
"attributes": {
"status": "Sent",
"created_at": "2022-05-02T08:57:50.171+03:00",
"amount": {
"currency": "KES",
"value": "500.0"
},
"transfer_batches": [{
"status": "Sent",
"amount": "500.0",
"disbursements": [{
"amount": "500.0",
"status": "Transferred",
"origination_time": "2022-05-02T08:57:50.171+03:00",
"transaction_reference": "1651471070",
"destination_type": "till",
"destination_reference": "3eccf0c1-ab6b-41a4-b51a-4e8f588105f1"
}]
}],
"metadata": {
"something": "TST-01",
"something_else": "Something else"
},
"_links": {
"callback_url": "http://portal.zarafu.com/payments",
"self": "https://sandbox.kopokopo.com/api/v1/payments/1cc58ad2-ccfd-4ede-a6a6-35809c81cb8a"
}
}
}
}
How can I filter the transaction_reference and status.
I have tried..
$jsonData = json_decode($response);
echo '<pre>';
echo $jsonData->status;
echo '</pre>';
You can't get the status like that. You have to use the format of your json. Exemple for the status :
echo $jsonData->data->attributes->status;
For transaction reference, it's :
echo $jsonData->data->attributes->transfer_batches->0->disbursements->0->transaction_reference;
I put '0' because it's arrays

How can i get value ItemSum by ItemID in php? [duplicate]

This question already has an answer here:
How to extract and access data from JSON with PHP?
(1 answer)
Closed 4 years ago.
I have json return:
{ "items": [ { "ItemID": 810, "ItemSum": 2 }, { "ItemID": 902, "ItemSum": 5 } ], "es": "", "ec": 0 }
How can I get value ItemSum by ItemID in php ?
How can I get value ItemSum by ItemID in php ?
You need to go through the items and look for the ItemID, e. g.:
$object = json_decode('{ "items": [ { "ItemID": 810, "ItemSum": 2 },
{ "ItemID": 902, "ItemSum": 5 } ], "es": "", "ec": 0 }');
function getSumbyID($object, $ID)
{
foreach ($object->items as $item) if ($item->ItemID == $ID) return $item->ItemSum;
}
echo getSumbyID($object, 902), "\n";
Like so:
$result = json_decode('{ "items": [ { "ItemID": 810, "ItemSum": 2 }, { "ItemID": 902, "ItemSum": 5 } ], "es": "", "ec": 0 }');
foreach($result->items as $item) {
var_dump($item->ItemSum);
}
Also, definitely read what's at the link #Paul Crovella commented with.

php parse a Json file [duplicate]

This question already has an answer here:
How to extract and access data from JSON with PHP?
(1 answer)
Closed 6 years ago.
i'm using this API called "pollDaddy",
using php to retrieve json responses ..I've come across a little hiccup..
How do you get the total of each answer?
My json data:
{
"pdResponse": {
"partnerGUID": "3F2504E0-4F89-11D3-9A0C-0305E82C3301",
"userCode": "123456-FErKS5yu15scpSGmvip4JA==",
"demands": {
"demand": {
"result": {
"answers": {
"answer": [{
"text": "Yes",
"id": "23123124",
"total": "1074",
"percent": "89.13"
}, {
"text": "No",
"id": "23123125",
"total": "131",
"percent": "10.87"
}]
}, "id": "690432265"
}, "id": "GetPollResults"
}
}
}
}
First we have to decode the json data. so we use json_decode. Then we select the right element and loop through it to get all the anwers
$data = '{ "pdResponse": { "partnerGUID": "3F2504E0-4F89-11D3-9A0C-0305E82C3301", "userCode": "123456-FErKS5yu15scpSGmvip4JA==", "demands": { "demand": { "result": { "answers": { "answer": [{ "text": "Yes", "id": "23123124", "total": "1074", "percent": "89.13" }, { "text": "No", "id": "23123125", "total": "131", "percent": "10.87" }] }, "id": "690432265" }, "id": "GetPollResults" } } } }';
$response = json_decode($data);
$answers = $response->pdResponse->demands->demand->result->answers->answer;
foreach($answers as $a)
{
echo $a->total;
}

Search into multidimensional array and change value of one key

I have one json request which contain multiple array:
{
"user_type": "2",
"user_id": "57",
"client_detail": [
{
"server_user_id": "1",
........
........
"is_active": "1",
"client_local_id": "11"
},
{
"server_user_id": "2",
........
........
"is_active": "1",
"client_local_id": "12"
}
],
}
Using above request I change data into database. then return data from DB. but i have to pass client_local_id into response.
so suppose i got 3 result from DB then i have to return client_local_id(this field is not stored in DB, there is no need for that) with them. so i pass default client_local_id 0.
exa:
"client_detail": [
{
"server_user_id": "1",
........
........
"is_active": "1",
"client_local_id": 0
},
{
"server_user_id": "2",
........
........
"is_active": "1",
"client_local_id": 0
},
{
"server_user_id": "3",
........
........
"is_active": "1",
"client_local_id": 0
},
]
then using below code i change value of client_local_id.
$response = array('client_detail' => $dbvalue);
/* Change Client Local ID */
if(sizeof($client_detail_data)>0)
{
foreach($client_detail_data as $key=>$resclient_data) // loop of request
{
foreach($response['client_detail'] as $key1=>$res_client) //loop of response
{
//if id is match then change value
if($res_client['server_user_id']==$resclient_data['server_user_id'])
{
$response['client_detail'][$key1]['client_local_id'] = $resclient_data['client_local_id'];
}
}
}
}
But i think there is easy method, to do that. I have a multiple array in request so i don't want to use too much foreach loop. so how to solve it in proper way?
Thanks in advance.
First of all let’s map server_user_ids to client_user_ids:
$s2c = array();
foreach($resclient_data as $item) {
$s2c[$item['server_user_id']] = $item['client_user_id'];
}
Now we can use array_map directly on $response:
$response['client_detail'] = array_map(function($elem) use($s2c) {
$elem['client_local_id'] = $s2c[$elem['server_local_id']];
return $elem;
}, $response['client_detail']);
I diidn’t test the code, but hopefully the idea is clear.

PHP JSON Data Selection

How would I go about selecting the data of each title from the following JSON?
I have the JSON decoded, but I'm not sure how to select the part I want.
{
"responseData": {
"results": [
{
"title": "Justin Giesbrecht 749",
"titleNoFormatting": "Justin Giesbrecht 749",
},
{
"title": "Gopher dunes 09",
"titleNoFormatting": "Gopher dunes 09",
},
{
"title": "dirtbike Justin",
"titleNoFormatting": "dirtbike Justin",
},
{
"title": "A Warming",
"titleNoFormatting": "A Warming",
}
],
"cursor": {
"pages": [
{
"start": "0",
"label": 1
},
{
"start": "4",
"label": 2
}
],
"estimatedResultCount": "6",
"currentPageIndex": 0,
}
},
"responseDetails": null,
"responseStatus": 200
}
I thought it would be something like this, but I don't get anything:
echo "Response ". $jsonS->responseData->results[1]->title;
Actually you've got the reading of the title part right, it's the JSON that is invalid.
Copying the JSON into a JSON validator/lint e.g. http://www.jsonlint.com/ will show that the you have additional , (commas) after the last object attribute in a few places (5 places to be exact, after each 'titleFormatting' attribute and after 'currentPageIndex').
If you fix those errors and parse it using json_decode e.g.:
$jsonS = json_decode($json_text);
Then your own code:
echo "Response " . $jsonS->responseData->results[1]->title;
Will output the second (index 1 being the second index) results title
Response Gopher dunes 09
When you json_decode something it is converted to a regular PHP array, so you can reference it like $decodedObject["nodeName"].
When I parse that JSON as you quoted it with PHP's json_decode method, it gives me NULL because PHP doesn't think it's valid JSON. Add a var_dump($jsonS); to see if this is happening to you as well. If it is, you may need to be sure your JSON is valid.
Here's what I did, for reference:
$json_data = <<<END_OF_JSON
{
"responseData": { "results": [
{
"title": "Justin Giesbrecht 749", "titleNoFormatting": "Justin Giesbrecht 749",
},
{
"title": "Gopher dunes 09",
"titleNoFormatting": "Gopher dunes 09",
},
{
"title": "dirtbike Justin",
"titleNoFormatting": "dirtbike Justin",
},
{
"title": "A Warming",
"titleNoFormatting": "A Warming",
}
],
"cursor": {
"pages": [ {
"start": "0",
"label": 1
},
{
"start": "4",
"label": 2
}
],
"estimatedResultCount": "6",
"currentPageIndex": 0,
}
},
"responseDetails": null,
"responseStatus": 200
}
END_OF_JSON;
$jsonS = json_decode($json_data);
var_dump($jsonS);
echo "Response ". $jsonS->responseData->results[1]->title;
And the output was:
NULL Response
If you're using different JSON, please edit your question and share it. But if you're actually using the above, it's not valid...
In JSON you are not allowed to leave trailing comma in array/object definition. So, when in PHP is perfectly valid to write:
$a = array(1,2,3,);
(note last comma), in JSON
a : [1,2,3,]
or
a : {x :'y',}
is invalid.

Categories