Php how to add backslash inside array of strings - php

I have a below array:
Array
(
[0] => CLICK
[1] => CSC
)
After json_encode I got below one.
"["CLICK","CSC"]"
How to convert this into "[\"CLICK\",\"CSC\"]" this.
Any one help.

Some info was missing which I got after discussion.
They are manually replacing a lot of characters before returning json. Out of them they also include [ => "[ and ] => ]" due to their backend implications.
A simple json_encode was solution for this along with skipping those character replacement for specific this key.

Source:
<?php
$arr = [
"CLICK", "CSC"
];
echo json_encode(json_encode($arr)) . "\n";
Result:
"[\"CLICK\",\"CSC\"]"

Related

Print result is different in the array function

I have a problem with the array PHP function, below is my first sample code:
$country = array(
"Holland" => "David",
"England" => "Holly"
);
print_r ($country);
This is the result Array ( [Holland] => David [England] => Holly )
I want to ask, is possible to make the array data become variables? For second example like below the sample code, I want to store the data in the variable $data the put inside the array.:
$data = '"Holland" => "David","England" => "Holly"';
$country = array($data);
print_r ($country);
But this result is shown me like this: Array ( [0] => "Holland" => "David","England" => "Holly" )
May I know these two conditions why the results are not the same? Actually, I want the two conditions can get the same results, which is Array ( [Holland] => David [England] => Holly ).
Hope someone can guide me on how to solve this problem. Thanks.
You can use the following Code.
<?php
$country = array(
"Holland" => "David",
"England" => "Holly"
);
foreach ($country as $index => $value)
{
$$index = $value;
}
?>
Now, Holland & England are two variables. You can use them using $Holland etc.
A syntax such as $$variable is called Variable Variable. Actually The inner $ resolves the a variable to a string, and the outer one resolves a variable by that string.
So there is this thing called
Destructuring
You can do it something like ["Holland" => $eolland, "England" => $england] = $country;
And now you have your array elements inside the variables.
Go read the article above if you want more information about this because it gets really useful (especially in unit tests usind data provders from my experience).
If you want to extract elements from an associative array such that the keys become variable names and values become the value of that variable you can use extract
extract($country);
To check what changed you can do
print_r(get_defined_vars());
Explanation on why the below does not work
$data = '"Holland" => "David","England" => "Holly"';
When you enclose the above in single quotes ' php would recognise it as a string. And php will parse a string as a string and not as an array.
Do note it is not enough to create a string with the same syntax as the code and expect php to parse it as code. The codes will work if you do this
$data = ["Holland" => "David","England" => "Holly"];
However, now $data itself is an array.
A simple copy of an array can be made by using
$data = $country;

PHP: Json encode addslashes only to a specific value

I have a PHP array as follows:
Array
(
[Caller] => EFLwebsite
[CaseDetails] => Array
(
[Description] => This is a Site Readiness case.
[SAPCustomerCode] => 1001140090
[ProductNumber] => GWPDREVIV00000
[CustomerAssetSerialNumber] => 000000000418005207
[RequestedDate] => 2021/01/06
[RequestedTime] => 10:00:45
[BP] => CRM Test User
)
)
I need to convert the above array into json as follows:
{
"Caller":"EFLwebsite",
"CaseDetails":"{\"Description\":\"This is a Site Readiness case.\",\"SAPCustomerCode\":\"0100301500\",\"ProductNumber\":\"GWPDFCOND00000\",\"CustomerAssetSerialNumber\":\"000000000418005207\",\"RequestedDate\":\"2021\/01\/06\",\"RequestedTime\":\"23:54:12\",\"BP\":\"CRM Test User\"}"
}
I am using addslases() after json_encode but it returns as follows:
{
\"Caller\":\"EFLwebsite\",
\"CaseDetails\":{\"Description\":\"This is a Site Readiness case.\",\"SAPCustomerCode\":\"1001140090\",\"ProductNumber\":\"GWPDREVIV00000\",\"CustomerAssetSerialNumber\":\"000000000418005207\",\"RequestedDate\":\"2021\\/01\\/06\",\"RequestedTime\":\"10:00:45\",\"BP\":\"CRM Test User\"}
}
I need to add the slashes only to the second value which is CaseDetails
I also tried encoding the subarray separately and adding slashes as a string, but it is adding more slashes again.
I also have no idea why you would want to do this, but this should do the trick:
$array = [
"Caller" => "EFLwebsite",
"CaseDetails" => [
"Description" => "This is a Site Readiness case.",
"SAPCustomerCode" => "1001140090"
]
];
// first convert case details to json
$array["CaseDetails"] = json_encode($array["CaseDetails"]);
echo "<pre>";
print_r(json_encode($array)); // then convert everything to json
echo "</pre>";
This returns:
{"Caller":"EFLwebsite",
"CaseDetails":"{\"Description\":\"This is a Site Readiness case.\",\"SAPCustomerCode\":\"1001140090\"}"}
Using heredoc string with php. Docs
Heredoc text behaves just like a double-quoted string, without the double quotes. This means that quotes in a heredoc do not need to be escaped, but the escape codes listed above can still be used. Variables are expanded, but the same care must be taken when expressing complex variables inside a heredoc as with strings.
$case = addslases(json_encode($array['CaseDetails']));
$json = <<<EOT
{ "Caller": "{$array['Caller']}", "CaseDetails": {$case} }
EOT;
echo $json;

Data in array does not come out the same

I have an array which I create. When reading the array with print_r it is not returning with the correct data inputted! I am missing specific sectionsn such as < & > brackets with its headings.
How can i preserve these?
Code:
$params = array(
"Parm1" => "test",
"Parm2" => "hi",
"Parm3" => GUID(),
"Parm4" => "lol",
"Parm5" => "
<R>
<R1>the</R1>
<R2>dog</R2>
<R3>is</R3>
<R15>happy</R15>
<R20>today</R20>
</R>
");
Basically the only data that is jumbled up is the Parm5 section. I want everything inside to return exactly as it is! EG: Reading as is i only receive Array ( [Parm1] => test [Parm2] => hi [Parm3] => B18BE727-8F79-4D4A-80EA-3974B1429F78 [Parm4] => lol [Parm5] => the dog is happy today ) from print_r
I want to return:
Array ( [Parm1] => test [Parm2] => hi [Parm3] => B18BE727-8F79-4D4A-80EA-3974B1429F78 [Parm4] => lol [Parm5] => <R><R1>the</R1> <R2>dog</R2> <R3>is</R3> <R15>happy</R15> <R20>today</R20></R> )
escape param5 with htmlspecialchars('<R> ..... </R>'). Your browser currently sees it as html tags and parses it.
Use htmlspecialchars on the return value of print_r:
echo "<pre>";
echo htmlspecialchars(print_r($params, true));
echo "</pre>";

How to convert Perl generated string(Object) into JSON using PHP?

I created a REST API using Laravel (Lumen). Basically I'm taking some values from database and need to do some functions. Here's the problem.
There's a field called web_data in my result set. It's Perl code. This is how it looks when I query the database using normal SQL editor like phpmyadmin and workbench.
{"caption" => "Genes (Comprehensive set from GENCODE 26)","colour_key" => "[biotype]","default" => {"MultiBottom" => "collapsed_label","MultiTop" => "gene_label","alignsliceviewbottom" => "as_collapsed_label","contigviewbottom" => "transcript_label","contigviewtop" => "gene_label","cytoview" => "gene_label"},"key" => "ensembl","label_key" => "[biotype]","multi_name" => "GENCODE 26 Comprehensive gene set","name" => "Comprehensive Gene Annotations from GENCODE 26"}
It's very clear and nothing wrong. But when I get the same result via my REST API, I'm getting the following output. It has many "\" symbols. Here's that output.
{\"caption\" => \"Genes (Comprehensive set from GENCODE 26)\",\"colour_key\" => \"[biotype]\",\"default\" => {\"MultiBottom\" => \"collapsed_label\",\"MultiTop\" => \"gene_label\",\"alignsliceviewbottom\" => \"as_collapsed_label\",\"contigviewbottom\" => \"transcript_label\",\"contigviewtop\" => \"gene_label\",\"cytoview\" => \"gene_label\"},\"key\" => \"ensembl\",\"label_key\" => \"[biotype]\",\"multi_name\" => \"GENCODE 26 Comprehensive gene set\",\"name\" => \"Comprehensive Gene Annotations from GENCODE 26\"}
Can you please tell me what's the reason for this? Is this an issue with PHP or something like that ?
And also I have another issue. This is Perl code containing "=>" symbols to seperate values. I need to convert this into a JSON object using PHP. Is that possible ?
Need to convert like following object.
{ "caption" : "Genes (Comprehensive set from GENCODE 26)", "colour_key" : "[biotype]", "default" : { "MultiBottom" : "collapsed_label" ...
This is the php code i'm using to create the REST output using SQL data.
public function testDualDatabaseConnection()
{
$testGene = DB::connection('mysql2')->select('select a.analysis_id, logic_name, ad.description, ad.display_label, ad.web_data FROM ( select distinct(analysis_id) as analysis_id from gene ) as a join analysis on (a.analysis_id = analysis.analysis_id) join analysis_description as ad on (analysis.analysis_id = ad.analysis_id) where ad.displayable = :wow1', ['wow1' => "1"]);
return response()->json($testGene);
}
And also this is the full JSON output i'm getting via REST API.
https://gist.github.com/chanakaDe/0d1e5916d8bc788bb101afa9b92dc9cd
In this response, you can see "web_data", that's also the part I need to convert to JSON again.
If on the off chance you really do have
{\"caption\" => \"Genes ...\", ...}
Then you have a JSON fragment, and the first you thing you need to do is turn it into a complete JSON document so it can be decoded.
$json_fragment_from_api = '{\"caption\" => \"Genes ...\", ...}';
$json_from_api = '{"result":"' . $json_fragment_from_api . '"}';
$response = json_decode($json_from_api, true);
$perl_code = $response["result"];
That said, I think it's far more likely that you only showed a portion of your actual input. You're far more likely to have received something that looks more like
{ "result": "{\"caption\" => \"Genes ...\", ...}" }
Since you already have a complete JSON document, simply start by decoding it.
$json_from_api = '{ "result": "{\"caption\" => \"Genes ...\", ...}" }';
$response = json_decode($json_from_api, true);
$perl_code = $response["result"];
At this point, you have the value from the database.
{"caption" => "Genes ...", ...}
That value is Perl code. More specifically, it's surely Perl code that was produced by Data::Dumper. This is going to be hard to convert into JSON.
You could use the following, but it won't handle everything:
$desired_json = str_replace(' =>', ':', $perl_code);
Here are some things it won't handle:
Undefined values
Strings containing =>
Strings containing $
Strings containing #
Strings containing non-ASCII or some non-printable characters.
As shown here:
$ perl -e'
use feature qw( say );
use Data::Dumper qw( Dumper );
local $Data::Dumper::Useqq = 1;
local $Data::Dumper::Terse = 1;
local $Data::Dumper::Indent = 0;
say(Dumper({ x => undef }));
say(Dumper({ x => " => " }));
say(Dumper({ x => q{$} }));
say(Dumper({ x => q{#} }));
say(Dumper({ x => "\x7F" }));
'
{"x" => undef} # Gives {"x": undef} instead of {"x": null}
{"x" => " => "} # Gives {"x": ": "} instead of {"x": " => "}
{"x" => "\$"} # Gives {"x": "\$"} instead of {"x": "$"}
{"x" => "\#"} # Gives {"x": "\#"} instead of {"x": "#"}
{"x" => "\177"} # Gives {"x": "\177"} instead of {"x": "\u007f"}
Not sure where that escaping happens (if you can, give some more details)
But, try to replace => with : and \" with " and you'll have yourself a valid json.
$string = '{\"caption\" => \"Genes (Comprehensive set from GENCODE 26)\",\"colour_key\" => \"[biotype]\",\"default\" => {\"MultiBottom\" => \"collapsed_label\",\"MultiTop\" => \"gene_label\",\"alignsliceviewbottom\" => \"as_collapsed_label\",\"contigviewbottom\" => \"transcript_label\",\"contigviewtop\" => \"gene_label\",\"cytoview\" => \"gene_label\"},\"key\" => \"ensembl\",\"label_key\" => \"[biotype]\",\"multi_name\" => \"GENCODE 26 Comprehensive gene set\",\"name\" => \"Comprehensive Gene Annotations from GENCODE 26\"}';
$string = str_replace('\"','"', $string);
$string = str_replace('=>',':', $string);
$json = json_decode($string, true);
print_r($json);
You can check it out here: https://3v4l.org/UBmGA
Apparently this answer got more hate than i'd expect. Nevertheless, it did help OP and i'm sticking by it. In the end, this is what SO stands for.
I would like to know though... why so many downvotes? I do take constructive criticism well and would like to know how to improve future answers.

Cannot echo array elements - Undefined index

I have my array looking like this when I print_r(delegates[$i])
Array
(
['firstName'] => Brady
['surname'] => Manning
['jobTitle'] => CEO
['memberNumber'] => 123456
['dieteryRequirements'] => halal
)
Howerver, when I try to get the firstName like this echo delegates[$i]['firstName'] I get the following error
Notice: Undefined index: firstName
Schoolboy question but I'd really appreciate some help here.
After examining the error you are having, this is my best answer. I initially assumed you didnt need the index $i, but that was not the case since you are actually getting results when you print_r($delegates[$i]) Therefore I am lead to believe your array is a multidimensional array.
Another thing I noticed, (and I give credit to #Rizier123 who pointed out in the comments to use both single and double quotes) is that your print_r result is outputting single quotes '' around your element keys like this 'firstname' This means that you are actually storing the quotes inside your array. With all that said I believe your $delegates array looks something like this:
$delegates = array(
array(
"'firstName'" => 'Brady',
"'surname'" => 'Manning',
"'jobTitle'" => 'CEO',
"'memberNumber'" => 123456,
"'dieteryRequirements'" => 'halal',
)
);
Therefore in order to access the element you will need to use the index, and use the element with the single quotes '' like this:
echo $delegates[0]["'firstname'"]
What I would do is remove all those single quotes so that you can access them correctly.
Hope this helps.

Categories