Access json result with spaces - php

I am getting a json result from an API. One of the keys in presented in a question, rather than a true key like this:
{"somthing":"12345","questions":[{"Question Here about something. There are also quotes like this \"here\")":"thevalue"}],"id":"123455"}
"Question Here about something. There are also quotes like this \"here\""
Will always remain the same, but how to I access its value (thevalue).
I'm trying something like:
$result = json_decode($jsonresult);
echo $result->questions->Question Here about something. There are also quotes like this \"here\");
But that does not work because of the spaces and escaped quotes. Any suggestions?

Try Below:
$jsonresult = '{"somthing":"12345","questions":[{"Question Here about something. There are also quotes like this \"here\")":"thevalue"}],"id":"123455"}';
$result = json_decode($jsonresult);
echo $result->questions[0]->{'Question Here about something. There are also quotes like this "here")';
This will result thevalue

A much easier way is to just convert the JSON string into a PHP associative array like this:
$json_string = '{"somthing":"12345","questions":[{"Question Here about something. There are also quotes like this \"here\")":"thevalue"}],"id":"123455"}';
$json = json_decode($json_string, true);
$questions = $json['questions'];
for($i = 0; $i < count($questions); $i++) {
$question = $questions[$i];
foreach($question as $key => $value) {
echo "Question: " . $key . "\n";
echo "Answer:" . $value . "\n";
}
}

Related

Implodes remove double quotes

$view_array = implode(',', $view_array);
When I var_dump this the value is "3,1" how can I remove the outer quotes so it will become 3,1 only
The quotes are part of the way you are outputting it. They don't exist, there is no spoon. Use echo instead...
$view_array = [1,2,3];
$view_array = implode(',', $view_array);
echo $view_array;
Outputs
1,2,3
Well you can use explode, and just use the value by itself:
$view_array = explode(',', $view_array);
echo $view_array[0];
Or put it in a loop and render them all
$view_array = explode(',', $view_array);
for ($i=0; $i < count($view_array) ; $i++) {
# code...
echo $view_array[$i];
}

How to replace part of a multi array variable with a different variable?

Here is an example of what I am trying to accomplish:
$array['aaa']['bbb']['ccc'] = "value";
$subarray = "['bbb']['ccc']";
echo $array['aaa']$subarray; // these 2 echos should be the same
echo $array['aaa']['bbb']['ccc']; // these 2 echos should be the same
It should display the same as $array['aaa']['bbb']['ccc'] i.e., "value".
This doesnt work, of course. But is there some simple solution to this?
There could be some function and the $subarrayvalue may be used as a parametr and/or as an array itself like: $subarray = array('bbb','ccc'); I dont mind as long as it worsk.
You could try something like below.
$subarray = "['bbb']['ccc']";
$temp = parse_str("\$array['aaa']".$subarray);
echo $temp;
OR To ignore single quotes -
$subarray = "[\'bbb\'][\'ccc\']";
$temp = parse_str("\$array[\'aaa\']".$subarray);
echo $temp;
Also you may refer - http://php.net/manual/en/function.parse-str.php
Just try using array chunk function http://php.net/manual/en/function.array-chunk.php
here is what actually works!!
$array['aaa']['bbb']['ccc'] = "value";
$subarray = "['bbb']['ccc']";
$string = 'echo $array[\'aaa\']' . $subarray . ';';
eval($string);

Storing values in a particular format in the array, which are retrieved from a .csv file to the array in PHP

An attribute from a .csv file which looks like:
[[-8.585676,41.148522],[-8.585712,41.148639],[-8.585685,41.148855]]
I want to split this data into an 2D array USING PHP, which I want to look like this:
arr[0][0] = -8.585676
arr[0][1] = 41.148522
arr[1][0] = -8.585712
arr[1][1] = -41.148639
arr[2][0] = -8.585685
arr[2][1] = 41.148855
I have done it like this:
$arr = preg_split('[,]', $str);
$n = count($arr);
for($i=0;$i<$n;$i++){
echo $arr[$i];
echo "<br>";
}
echo "<br><br>";
Its output looks like:
[[-8.585676
41.148522]
[-8.585712
41.148639]
[-8.585685
41.148855]
This just happens to be a perfect match for a json_decode() call. Simply use $arr = json_decode($str); and it'll do the trick.

Array seems empty with Implode on array_values

Some assistance would be greatly appreciated:
The 'foreach' section works perfectly and echo's the result set perfectly; as soon as I try the implode it fails? Thank you!
$ctr = 0;
while ($row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC)) {
$RespondentsResultSetArray[$ctr] = array(
"Firstname" => $row['cnt_firstname'],
"Lastname" => $row['cnt_lastname']
);
$ctr = $ctr + 1;
}
foreach ($RespondentsResultSetArray as $key) {
echo $key["Firstname"] . ' ' . $key["Lastname"] . ', ';
}
sqlsrv_free_stmt($stmt);
echo implode(', ',array_values($RespondentsResultSetArray));
try this
implode(',',$RespondentsResultSetArray);
You are passing an array of arrays to implode function. Here is a little deviation of your code, that should get you to the same result:
$full_array = array();
foreach ($RespondentsResultSetArray as $key) {
echo $key["Firstname"] . ' ' . $key["Lastname"] . ', ';
array_push($full_array,$key["Firstname"]);
array_push($full_array,$key["Lastname"]);
}
echo implode(', ',$full_array);
Also, for the future, try to chose smaller names for your variables, and use lowercase for your variable names and array index.
The php implode function accepts an array of strings.
You are not passing it an array of strings.
To user1844933 that just answered, your suggestion would pass implode an array of arrays. That won't work for the same reason.
$RespondentsResultSetArray=array();
while ($row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC)) {
array_push($RespondentsResultSetArray,$row['cnt_firstname'].' '.$row['cnt_lastname']);
}
$saved_to_variable=implode(', '$RespondentsResultSetArray);
Will create an array of strings which you can then implode
Since you recently commented that you want to save it to a variable rather than echo it, I just changed the last line of the example code. I believe that will give you the properly spaced, and delimited string that you desire.
since$RespondentsResultSetArray is multidimensional array use foreach loop before echo
$string = "";
foreach($RespondentsResultSetArray as $values)
{
echo implode(array_values($values),",");
$string= $string.",".implode(array_values($values),",");
}
$string=ltrim($string,",");
echo $string;
Demo

How to handle my data?

Edit: The aim of my method is to delete a value from a string in a database.
I cant seem to find the answer for this one anywhere. Can you concatenate inside a str_replace like this:
str_replace($pid . ",","",$boom);
$pid is a page id, eg 40
$boom is an exploded array
If i have a string: 40,56,12 i want to make it 56,12 however without the concatenator in it will produce:
,56,12
When I have the concat in the str_replace it doesnt do a thing. Is this possible?
Answering your question: yes you can. That code works as you would expect it to.
But this approach is wrong. It will not work for $pid = 12; (last element, without trailing coma) and will incorrectly replace 40, in $boom = '140,20,12';
You should keep it in array, search for unwanted value, if found unset it from the array and then implode with coma.
$boom = array_filter($boom);
$key = array_search($pid, $boom);
if($key !== false){
unset($boom[$key]);
}
$boom = implode(',',$boom);
[+] Your code does not work because $boom is an array, and str_replace operates on string.
As $boom is an array, you don't need to use array on your case.
Change this
$boom = explode(",",$ticket_array);
$boom = str_replace($pid . ",","",$boom);
$together = implode(",",$boom);
to
$together = str_replace($pid . ",","",$ticket_array);
Update: If you want still want to use array
$boom = explode(",",$ticket_array);
unset($boom[array_search($pid, $boom)]);
$together = implode(",",$boom);
After you have edited it becomes clear that you want to remove the value of $pid from the array $boom which contains one number as a value. You can use array_search to find if it is in at if in with which key. You can then unset the element from $boom:
$pid = '40';
$boom = explode(',', '40,56,12');
$r = array_search($pid, $boom, FALSE);
if ($r !== FALSE) {
unset($boom[$r]);
}
Old question:
Can you concatenate inside a str_replace like this: ... ?
Yes you can, see the example:
$pid = '40';
$boom = array('40,56,12');
print_r(str_replace($pid . ",", "", $boom));
Result:
Array
(
[0] => 56,12
)
Which is pretty much like you did so you might be looking for the problem at the wrong place. You can use any string expression for the parameter.
It might be easier for you if you're unsure to create a variable first:
$pid = '40';
$boom = array('40,56,12');
$search = sprintf("%d,", $pid);
print_r(str_replace($search, "", $boom));
You should store your "ticket array" in a separate table.
And use regular SQL queries (UPDATE, DELETE) to manipulate it.
A relational word in the name of your database is for the reason. And you are abusing this smart software with such a barbaric approach.
You could use str_split, it converts a string to an array, then with a foreach loop echo all the values except the first one.
$numbers_string="40,56,12";
$numbers_array = str_split($numbers_string);
//then, when you have the array of numbers, you could echo every number except the first separating them with a comma
foreach ($numbers_array as $key => $value) {
if ($key > 0) {
echo $value . ", ";
}
}
If you want is to skip a value not by it's position in the array, but for it's value then you could do this instead:
$unwanted_value="40";
foreach ($numbers_array as $key => $value) {
if ($value != $unwanted_value) {
echo $value . ", ";
}
else {
unset($numbers_array[$key]);
$numbers_array = array_values($numbers_array);
var_dump($numbers_array);
}
}

Categories