JSON decode get the last element, PHP end - php

I want to get the last element in the JSON decoded array,
Error I am getting
Warning: end() expects parameter 1 to be array
$data output
stdClass Object (
[contact001] => stdClass Object ( [age] => 33 [name] => Robert [tel] => 87778787878787878 )
[contact002] => stdClass Object ( [age] => 33 [name] => Calvin [tel] => 87778787878787878 )
)
PHP code:
$namejson = $firebase->get(DEFAULT_PATH . '/name/');
$data=json_decode($namejson);
foreach ($data as $key => $value) {
echo end($key);
}
Warning: end() expects parameter 1 to be array

When you decode your $namejson json string to array, you can use array_keys to get array of keys, that are present in your array. Next, you need the last key from this array, use array_pop for this. And because the last key is a string, you can use simple ++ operator to increment the value:
$data = json_decode($namejson, true);
$keys = array_keys($data);
$last_key = array_pop($keys);
echo 'Last key: ' . $last_key;
$last_key++;
$next_key = $last_key;
echo 'Next key: ' . $next_key;

$namejson = $firebase->get(DEFAULT_PATH . '/name/');
$data=json_decode($namejson,true);
foreach ($data as $key => $value) {
echo end($value);
}

Related

getting element names and values of json respsonse php

I would like to get all the elements and their values from the json response. I have the following response (snippet, it has more elements):
stdClass Object ( [Count] => 15244 [Warnings] => Array ( ) [Machines] => Array ( [0] => stdClass Object ( [Id] => 23 [Modified] => 2019-09-18 06:38:04 [Created] => 2016-03-10 14:11:39 ) [1] => stdClass Object ( [Id] => 51 [Modified] => 2019-09-18 08:15:52 [Created] => 2016-06-15 09:13:16 )))
Now I would like to get the results something like:
ID: 23, Modified: 2019-09-18 06:38:04, Created: 2016-03-10 14:11:39
ID: 51, Modified: 2019-09-18 08:15:52, Created: 2016-06-15 09:13:16
The problem is, that I don't want to hard-code the element names like "ID", "Created" and so on, because the complete array per Machines has about 50 elements.
This is what I tried:
$obj = json_decode($body);
foreach ($obj->Machines as $comp) {
$sup =key($comp);
echo key($comp)."-".$comp->$sup."<br>";
}
But this only gives the output:
Id-23
Id-51
So I only get the first KEY showed. I don't know how to get to the next element like "Modified" in the loop.
Thanks for the support!
You can use array map to echo the same,
foreach ($obj->Machines as $comp) {
echo implode(', ', array_map(function ($val, $key) {
return sprintf("%s:'%s'", $key, $val);
}, $comp, array_keys($comp)))."<br/>";
}
Solution 2:-
foreach ($obj->Machines as $comp) {
echo str_replace('=',':',http_build_query($comp,'',', '));
}
http_build_query — Generate URL-encoded query string
Convert your JSON data to array using json_decode(). Make an iteration over the array using array_map(), again make another nested iteration using array_walk() to replace the value to key:value pear format. Finally join the converted array to string by the glue of comma.
Code example:
$response = json_decode($response, true);
$result = array_map(function ($val) {
array_walk($val, function (&$v, $k) { $v = "$v: $k"; });
return implode(',', $val);
}, $response);
print_r($result);
What you did is correct, though this is a multi-dimensional array.
You need several foreach loops to iterate to the dimension you want.
$response = [];
foreach($obj->Machines as $comp) {
foreach($comp as $key => $value) {
$response[$key] = '';
foreach($value as $title => $display) {
$response[$key] .= $title . ': ' . $display . ', ';
}
$response[$key] = rtrim($response[$key], ', ');
}
}
var_dump($response);
This is what did the trick now:
$obj = json_decode($body);
print_r($obj);
//echo $obj->Machines[0]->Id;
foreach ($obj->Machines as $comp) {
echo "<BR>";
foreach($comp as $key => $value){
echo $key.":".$value." - ";
}
}
Gives the output like:
Id:148 - Modified:2019-09-18 07:16:47 - Created:2016-11-08 08:21:36
Id:143 - Modified:2019-09-15 04:13:21 - Created:2016-11-04 05:34:01
Again, really great support again! thank you very much!!

Find greatest value from json array in php

I'm using the following code to display the time for each character from a JSON. But the problem is there are repeated elements. I only want to select the highest value for each.
For example, highest value of s is 85, t is 84.
I tried the max() function, but only returning largest of all:
<?php
$speedArray = json_decode('[{"key":"e","time":35},{"key":"s","time":43},{"key":"t","time":39},{"key":"t","time":84},{"key":"s","time":85},{"key":"s","time":27},{"key":"t","time":80}]', true);
foreach ($speedArray as $timing) {
echo $timing['key'].$timing['time']."<br/>";
}
?>
First I would create a $key mapping and put all the values as array:
<?php
$speedArray = json_decode('[{"key":"e","time":35},{"key":"s","time":43},{"key":"t","time":39},{"key":"t","time":84},{"key":"s","time":85},{"key":"s","time":27},{"key":"t","time":80}]', true);
$keys = array();
foreach ($speedArray as $key) {
$keys[$key["key"]][] = $key["time"];
}
print_r($keys);
The output would be:
Array
(
[e] => Array
(
[0] => 35
)
[s] => Array
(
[0] => 43
[1] => 85
[2] => 27
)
[t] => Array
(
[0] => 39
[1] => 84
[2] => 80
)
)
Now it is easier to get the greatest of it. Using the max() function:
<?php
$speedArray = json_decode('[{"key":"e","time":35},{"key":"s","time":43},{"key":"t","time":39},{"key":"t","time":84},{"key":"s","time":85},{"key":"s","time":27},{"key":"t","time":80}]', true);
$keys = array();
foreach ($speedArray as $key) {
$keys[$key["key"]][] = $key["time"];
}
foreach ($keys as $key => $vals) {
echo "{$key}: " . max($vals) . "\n";
}
I get to this output:
e: 35
s: 85
t: 84
Demo: http://ideone.com/g4zULB
Getting max values for each key with a single loop and max function:
$speedArray = json_decode('[{"key":"e","time":35},{"key":"s","time":43},{"key":"t","time":39},{"key":"t","time":84},{"key":"s","time":85},{"key":"s","time":27},{"key":"t","time":80}]', true);
$result = [];
foreach ($speedArray as $v) {
(isset($result[$v['key']]))?
$result[$v['key']] = max($result[$v['key']], $v['time'])
: $result[$v['key']] = $v['time'];
}
print_r($result);
THe output:
Array
(
[e] => 35
[s] => 85
[t] => 84
)

How to replace array keys with another array values

I have two arrays and I want to replace the second array keys with the first array values if both keys matches.
As an example: Replace A with Code And B with name
How to do this;
<?php
$array = array('A' => 'code', 'B' =>'name');
$replacement_keys = array
(
array("A"=>'sara','B'=>2020),
array("A"=>'ahmed','B'=>1010)
);
foreach($replacement_keys as $key => $value){
foreach($value as $sk => $sv){
foreach($array as $rk => $rv){
if($sk == $rk ){
$sk = $rv;
}
}
}
}
echo "<pre>";
print_r($value);
echo "</pre>";
exit;
I want the result to be like this
array(
[0] => Array
(
[name] => ahmed
[code] => 1020
)
[1] => Array
(
[name] => sara
[code] => 2020
)
)
<?php
$array = array('A' => 'code', 'B' =>'name');
$replacement_keys = array
(
array("A"=>'sara','B'=>2020),
array("A"=>'ahmed','B'=>1010)
);
foreach($replacement_keys as &$value)
{
foreach ($array as $key => $name) {
$value[$name] = $value[$key];
unset($value[$key]);
}
}
var_dump($replacement_keys);
Try this:
<?php
$array = array('A' => 'code', 'B' =>'name');
$replacement_keys = array
(
array("A"=>'sara','B'=>2020),
array("A"=>'ahmed','B'=>1010)
);
$newArray = array();
foreach($replacement_keys as $key => $value)
{
foreach($value as $key2 => $value2)
{
if(isset($array[$key2]))
{
$newArray[$key][$array[$key2]] = $value2;
}
else
{
$newArray[$key][$key2] = $value2;
}
}
}
print_R($newArray);
This should work for you, nice and simple (I'm going to assume that A should be name and B should be code):
(Here I go through each array from $replacement_keys with array_map() and replace the array_keys() with the array_values() of $array. Then I simply get all array values from $replacement_keys and finally I array_combine() the replaced array keys with the corresponding array values)
$result = array_map("array_combine",
array_map(function($v)use($array){
return str_replace(array_keys($array), array_values($array), array_keys($v));
}, $replacement_keys),
$replacement_keys
);
output:
Array ( [0] => Array ( [code] => sara [name] => 2020 ) [1] => Array ( [code] => ahmed [name] => 1010 ) )
array_fill_keys
(PHP 5 >= 5.2.0, PHP 7)
array_fill_keys — Fill an array with values, specifying keys
Description
array array_fill_keys ( array $keys , mixed $value )
Fills an array with the value of the value parameter, using the values of the keys array as keys.
http://php.net/manual/en/function.array-fill-keys.php

unable to fetch data from Mongo dump

Below is the dump that I got from mongo. I need to fetch the opening artist name.
Array
(
[_id] => MongoId Object
(
[$id] => 51c9b63b6f7cb5f8229f27b7
)
[s20] => Array
(
[opening] => Array
(
[artist] => Array
(
[name] => Jay Z
)
[music] => Array
(
[name] => 99 problems
)
)
)
So, I tried:
foreach($mongo_dump as $key=>$value){
echo "<pre>KEY: " . print_r($key["s20"]["opening"]["artist"]["name"]) . "</pre>"; // line # 16
echo "<pre>VALUE: " . print_r($value) . "</pre>";
echo "\n\n";
}
However, I did not get the artist name. I received the following PHP warning:
PHP Warning: Illegal string offset 's20' in /var/www/Code/analytics/fetch_top_5_opening_artists.php on line 16
As Blaine mentions, $key isn't an array. The way that you are traversing the dump is incorrect. $key becomes a string in the context of the foreach loop. Try doing something like this:
if ($key == "s20") {
echo "<pre>KEY: " . print_r($value["opening"]["artist"]["name"]) . "</pre>";
}
the value itself is array() so your forloop is not going work unless you setupup nested. Here is example of neted for loop.
foreach($mongo_dump as $key )
{
{
foreach($key as $subkey)
{
echo $subkey
echo "\n\n";
}
}

weird php array

my php array looks like this:
Array (
[0] => dummy
[1] => stdClass Object (
[aid] => 1
[atitle] => Ameya R. Kadam )
[2] => stdClass Object (
[aid] => 2
[atitle] => Amritpal Singh )
[3] => stdClass Object (
[aid] => 3
[atitle] => Anwar Syed )
[4] => stdClass Object (
[aid] => 4
[atitle] => Aratrika )
) )
now i want to echo the values inside [atitle].
to be specific i want to implode values of atitle into another variable.
how can i make it happen?
With PHP 5.3:
$result = array_map(function($element) { return $element->atitle; }, $array);
if you don't have 5.3 you have to make the anonymous function a regular one and provide the name as string.
Above I missed the part about the empty element, using this approach this could be solved using array_filter:
$array = array_filter($array, function($element) { return is_object($element); });
$result = array_map(function($element) { return $element->atitle; }, $array);
If you are crazy you could write this in one line ...
Your array is declared a bit like this :
(Well, you're probably, in your real case, getting your data from a database or something like that -- but this should be ok, here, to test)
$arr = array(
'dummy',
(object)array('aid' => 1, 'atitle' => 'Ameya R. Kadam'),
(object)array('aid' => 2, 'atitle' => 'Amritpal Singh'),
(object)array('aid' => 3, 'atitle' => 'Anwar Syed'),
(object)array('aid' => 4, 'atitle' => 'Aratrika'),
);
Which means you can extract all the titles to an array, looping over your initial array (excluding the first element, and using the atitle property of each object) :
$titles = array();
$num = count($arr);
for ($i=1 ; $i<$num ; $i++) {
$titles[] = $arr[$i]->atitle;
}
var_dump($titles);
This will get you an array like this one :
array
0 => string 'Ameya R. Kadam' (length=14)
1 => string 'Amritpal Singh' (length=14)
2 => string 'Anwar Syed' (length=10)
3 => string 'Aratrika' (length=8)
And you can now implode all this to a string :
echo implode(', ', $titles);
And you'll get :
Ameya R. Kadam, Amritpal Singh, Anwar Syed, Aratrika
foreach($array as $item){
if(is_object($item) && isset($item->atitle)){
echo $item->atitle;
}
}
to get them into an Array you'd just need to do:
$resultArray = array();
foreach($array as $item){
if(is_object($item) && isset($item->atitle)){
$resultArray[] = $item->atitle;
}
}
Then resultArray is an array of all the atitles
Then you can output as you'd wish
$output = implode(', ', $resultArray);
What you have there is an object.
You can access [atitle] via
$array[1]->atitle;
If you want to check for the existence of title before output, you could use:
// generates the title string from all found titles
$str = '';
foreach ($array AS $k => $v) {
if (isset($v->title)) {
$str .= $v->title;
}
}
echo $str;
If you wanted these in an array it's just a quick switch of storage methods:
// generates the title string from all found titles
$arr = array();
foreach ($array AS $k => $v) {
if (isset($v->title)) {
$arr[] = $v->title;
}
}
echo implode(', ', $arr);
stdClass requires you to use the pointer notation -> for referencing whereas arrays require you to reference them by index, i.e. [4]. You can reference these like:
$array[0]
$array[1]->aid
$array[1]->atitle
$array[2]->aid
$array[2]->atitle
// etc, etc.
$yourArray = array(); //array from above
$atitleArray = array();
foreach($yourArray as $obj){
if(is_object($obj)){
$atitleArray[] = $obj->aTitle;
}
}
seeing as how not every element of your array is an object, you'll need to check for that.

Categories