Get array out of a Json? - php

I am getting a Json respond with :
$response = curl_exec($rest);
$json = json_decode($response, true);
I manage to get its values(strings) with :
$foundUserId=$json['results'][0]['userId'];
$foundName=$json['results'][0]['name'];
$foundPhoneNum=$json['results'][0]['phoneNumber'];
But the last value- phoneNumber, is array of strings .
If i try then to loop over it i get nothing(although the array is there in the Json)
foreach ($foundPhoneNum as &$value)
{
print_r($value);
}
What am i doing wrong ?
EDIT :
The json:
Array ( [results] => Array ( [0] => Array ( [action] => message [createdAt] => 2015-11-21T09:36:33.620Z [deviceId] => E18DDFEC-C3C9 [name] => me [objectId] => klMchCkIDi [phoneNumber] => ["xx665542","xxx9446"] [state] => 1 [updatedAt] => 2015-11-22T08:24:46.948Z [userId] => 433011AC-228A-4931-8700-4D050FA18FC1 ) ) )

You might have json as a string inside json. That's why after json_decode() you still have json inside phoneNumber. You have 2 options:
Decode phoneNumber like
$foundPhoneNum=json_decode($json['results'][0]['phoneNumber']);
Build proper initial json. Instead of
{"phoneNumber": "[\"xx665542\",\"xxx9446\"]"}
should be
{"phoneNumber": ["xx665542","xxx9446"]}

There's a couple of ways to debug situations like this as mentioned in the comments; print_r() and var_dump().
var_dump(), although harder to read the first few times, is my favourite because it tells you the data types of each value in the array. This will confirm whether or not the expected string is indeed an array.
An example from the var_dump() documentation:
<?php
$a = array(1, 2, array("a", "b", "c"));
var_dump($a);
And the output is;
array(3) {
[0]=>
int(1)
[1]=>
int(2)
[2]=>
array(3) {
[0]=>
string(1) "a"
[1]=>
string(1) "b"
[2]=>
string(1) "c"
}
}
As you can see it shows array, int and string as the data types.
You might also like to install the Xdebug extension for PHP which dumps more useful error messages and tracebacks. Again harder to read the first few times, but well worth it!

foreach ($foundPhoneNum as $value)
{
print_r($value);
}
There was an extra & before $value. Try this.

Related

Remove Numerical Keys from an array in php

I am simply trying to turn this:
Array
(
[0] => 20200330
[1] => 20200329
[2] => 20200328
)
Into this and I am having an extremely hard time
Array
(
20200330,
0200329,
20200328,
)
All arrays in PHP have a unique key for each value within that array.
By default they are 0, 1, 2, 3, etc unless you explicitly set them (e.g. $a = ['key' => 1234];).
It is possible to "remove" keys (set to default without impacting the order) through the use of the array_values() function:
$a = ['a' => 123, 'b' => 321];
$a = array_values($a);
print_r($a); // [0 => 123, 1 => 321]
But it is not possible to entirely remove the keys from an array.
Arrays are by default associated with numbers starting from 0
<?php
$arr=array("String1","String2","Something else");
var_dump($arr);
?>
Output will be:
array(3) {
[0]=>
string(7) "String1"
[1]=>
string(7) "String2"
[2]=>
string(14) "Something else"
}
So if you want to access element of array you type $arr[index] and index is number by default

How to extract strings from json

I have to extract strings from a xml file. One particular value has been generated using json enconding.
Here is a exemple of what I can find:
<plus_details>
[["Neuf"],["Petite copropri\u00e9t\u00e9"],["Vue mer"]]
</plus_details>
I would like to extract the strings and display them inline and separated by commas, like this :
Neuf, Petite copropriété, Vue mer
I tried using json_decode function, but the only thing I can display is:
array(3) {
[0]=>
array(1) {
[0]=>
string(4) “Neuf”
}
[1]=>
array(1) {
[0]=>
string(20) “Petite copropriété”
}
[2]=>
array(1) {
[0]=>
string(7) “Vue mer”
}
}
Any help would be appreciated. Thanks.
Simple use a loop to go through your data. When you json_decode the string you provided us, you will end-up with an array like this :
Array
(
[0] => Array
(
[0] => Neuf
)
[1] => Array
(
[0] => Petite copropriété
)
[2] => Array
(
[0] => Vue mer
)
)
So in order to get your data you need to loop your array.
foreach(json_decode($json) as $data){
echo $data[0];
echo '<br>';
}
The output of the above code is:
Neuf
Petite copropriété
Vue mer

How to get value in an object in PHP

I have a variable with object like this in PHP code.
[{"author_id":2},{"author_id":1}]
How to get the value of author_id. thanks
use json_decode to convert the object in php and get it. Example:
<?php
$xx='[{"author_id":2},{"author_id":1}]';
$arr=json_decode($xx,true);
print_r($arr);
//Output: Array ( [0] => Array ( [author_id] => 2 ) [1] => Array ( [author_id] => 1 ) )
echo $arr[0]["author_id"];
//Outpu: 2
?>
This is serialized JSON Array with JSON objects inside.
$str = '[{"author_id":2},{"author_id":1}]';
$arr = json_decode($str, true);
foreach($arr as $item) {
echo $item['author_id'];
}
That data you posted is in JSON format. After decoding that standard format you can directly access the contents.
For the first entry that would simply be:
<?php
$data = json_decode('[{"author_id":2},{"author_id":1}]');
var_dump($data[0]->author_id);
The output obviously is:
int(2)
To access all entries have a try like that:
The output then is:
array(2) {
[0]=>
int(2)
[1]=>
int(1)
}

How to get values only array in php?

Array ( [0] => UK [1] => France [2] => USA ) in these array get only values
like array(UK, France, USA) am trying like below,
$expression=array_values(array('0' => 'UK', '1' => 'France', '2' => 'USA'));
var_dump($expression);
OUTPUT PLAN:
array(3) { [0]=> string(2) "UK" [1]=> string(6) "France" [2]=> string(3) "USA" }
Can i get my desired output?
Please read answer carefully.
$arr = array('UK', 'France', 'USA'); // It has 0 ,1 ,2 keys but you cannot see in the code`
But in browser you can see it.
array(3) { [0]=> string(2) "UK" [1]=> string(6) "France" [2]=> string(3) "USA" }
Just use loop to print each country
foreach($arr as $country){
echo $country."<br>";
}
You can understand it by below loop
foreach($arr as $k=>$country){
echo "$k => $country"."<br>"; // Here $k is key like 0,1,2..
}
If you have array like below:-
$arr = array('uk'=>'UK', 'france'=>'France', 'usa'=>'USA') // It has uk ,france ,usa keys
now array_values($arr) will give you output as below
array(3) { [0]=> string(2) "UK" [1]=> string(6) "France" [2]=> string(3) "USA" }
It will remove all keys and regenerate index of key from 0.
Refer below links to understand PHP array:-
Link1
Link2
Link3
Hope it will help you :)
You could just do:
$out = array();
foreach($old_array as $new_value) { //Where $old_array is the array you want to convert
array_push($out, $new_value);
}
All PHP arrays have an internal index whether you attach one or not. So in your example even if you created an array using $countries = array("USA", "UK", "France") it would still output with indexes.
You can however ignore the indexes when your looping through it and only work with the values using a foreach() loop.
An example of such a loop would be...
foreach($expression as $index => $country) {
echo($country . "<br />");
};
The above example will print each country on its own line. You can adapt it to suit whatever looping you need.
As a side note be aware that the index will commence from 0 so item 1 in the array will have an index of 0 and increment from there.
You have this array.
Array ( [0] => UK [1] => France [2] => USA )
you have key and value assigned to it.
if you make another array like
array('UK','France','USA')
It is an associative array. Its the same as above.
Read it for more info
If you want to do operation with the array you can use foreach and for or other array related functions. So, first of all say what are you trying to accomplish with this one.
$expression=array_values(array('0' => 'UK', '1' => 'France', '2' => 'USA'));
foreach($expression as $val) {
echo $val.",";
}

Difference between var_dump,var_export & print_r

What is the difference between var_dump, var_export and print_r ?
var_dump is for debugging purposes. var_dump always prints the result.
// var_dump(array('', false, 42, array('42')));
array(4) {
[0]=> string(0) ""
[1]=> bool(false)
[2]=> int(42)
[3]=> array(1) {[0]=>string(2) "42")}
}
print_r is for debugging purposes, too, but does not include the member's type. It's a good idea to use if you know the types of elements in your array, but can be misleading otherwise. print_r by default prints the result, but allows returning as string instead by using the optional $return parameter.
Array (
[0] =>
[1] =>
[2] => 42
[3] => Array ([0] => 42)
)
var_export prints valid php code. Useful if you calculated some values and want the results as a constant in another script. Note that var_export can not handle reference cycles/recursive arrays, whereas var_dump and print_r check for these. var_export by default prints the result, but allows returning as string instead by using the optional $return parameter.
array (
0 => '',
1 => false,
2 => 42,
3 => array (0 => '42',),
)
Personally, I think var_export is the best compromise of concise and precise.
var_dump and var_export relate like this (from the manual)
var_export() gets structured
information about the given variable.
It is similar to var_dump() with one
exception: the returned representation
is valid PHP code.
They differ from print_r that var_dump exports more information, like the datatype and the size of the elements.

Categories