Initially, I was using a backend-as-a-service (Baas) to collect and simply display data on a webpage via a REST API call. The data was in JSON and decoded into a one dimensional array. I used the code below to successfully loop through the array and display the 'text' values in the array one line at a time on a webpage:
$returned_content = get_data('https://api.backendless.com/v1/data/Alerts'); //returns JSON
$data = json_decode($returned_content); //JSON to array
foreach ($data->results as $item) {
echo '<p>'.$item->text;
}
I switched BaaS providers and now the JSON when decoded is in a multi-dimensional array. An extract of the output is below:
array (
'offset' => 0,
'data' =>
array (
0 =>
array (
'created' => 1486047487000,
'___class' => 'Alerts',
'text' => 'Thank you for attending the 2017 BICSI Winter Conference and Exhibition in Tampa, FL.',
'ownerId' => NULL,
'updated' => NULL,
'objectId' => '610DF2CC-B333-4BAA-FF93-224B8273B100',
'__meta' => '{"relationRemovalIds":{},"selectedProperties":["created","___class","text","ownerId","updated","objectId"],"relatedObjects":{}}',
),
1 =>
array (
'created' => 1486047378000,
'___class' => 'Alerts',
'text' => 'Thank you for attending the 2017 BICSI Winter Conference and Exhibition in Tampa, FL.',
'ownerId' => NULL,
'updated' => NULL,
'objectId' => '43B5620F-2A19-5575-FF9F-B952AB2F0A00',
'__meta' => '{"relationRemovalIds":{},"selectedProperties":["created","___class","text","ownerId","updated","objectId"],"relatedObjects":{}}',
),
2 =>
array (
'created' => 1476139578000,
'___class' => 'Alerts',
'text' => 'test5 pw and backendless',
'ownerId' => NULL,
'updated' => NULL,
'objectId' => '97B1BC3A-3233-2265-FF73-752BA720F300',
'__meta' => '{"relationRemovalIds":{},"selectedProperties":["created","___class","text","ownerId","updated","objectId"],"relatedObjects":{}}',
),
),
'nextPage' => 'https://api.backendless.com/v1/data/Alerts?pageSize=10&offset=10',
'totalObjects' => 44,
)
I am not a pro in PHP and I cannot figure out how to loop through this multi-dimensional array and simply display the 'text' values like I did with the one dimensional array. Any help is appreciated.
Very similar:
foreach ($data['data'] as $item) {
echo '<p>'.$item['text'];
}
The notation is different use $array['key'] for the equivalent of $object->key
Whatever was in $data->results is now in $data['data'].
That' should be it.
I might call json_decode(json_encode($dataArray)) to get a stdClass project representation of the array. Sometime working with -> notation is just easier.
Just noticed you were kind of mixing up, array and object terms. I think the new BaaS just uses a different key for the actual data. Try this:
$returned_content = get_data('https://api.backendless.com/v1/data/Alerts'); //returns JSON
$data = json_decode($returned_content['data']); //JSON to array
foreach ($data as $item) {
echo '<p>'.$item->text;
}
Related
I have a large multidimensional array that looks like the below.
I want to remove duplicate arrays based on the ID, however, I am struggling to achieve this.
I want the duplicates to work over the entire array, so you can see that ID 1229873 is a duplicate, in the array 2021-07-07 and 2021-07-09, it should therefore be removed from 2021-07-09
How would I achieve this? array_unique has not worked for me.
$data = array (
'2021-07-07' =>
array (
0 =>
array (
'id' => 5435435,
'homeID' => 8754,
'match_url' => '/usa/reading-united-ac-vs-ocean-city-noreasters-fc-h2h-stats#1229873',
'competition_id' => 5808,
'matches_completed_minimum' => 12,
),
1 =>
array (
'id' => 1229873,
'homeID' => 8754,
'match_url' => '/usa/reading-united-ac-vs-ocean-city-noreasters-fc-h2h-stats#1229873',
'competition_id' => 5808,
'matches_completed_minimum' => 12,
),
),
'2021-07-09' =>
array (
0 =>
array (
'id' => 3243234,
'homeID' => 8754,
'match_url' => '/usa/reading-united-ac-vs-ocean-city-noreasters-fc-h2h-stats#1229873',
'competition_id' => 5808,
'matches_completed_minimum' => 12,
),
1 =>
array (
'id' => 1229873,
'homeID' => 8754,
'match_url' => '/usa/reading-united-ac-vs-ocean-city-noreasters-fc-h2h-stats#1229873',
'competition_id' => 5808,
'matches_completed_minimum' => 12,
),
),
);
This is a perfect case for array_uunique()! No wait, scratch that. The PHP devs refused to implement it for the perfectly valid reason of... [shuffles notes] "the function name looks like a typo".
[sets notes on fire]
Anyhow, you just need to iterate over that data, keep track of the IDs you've seen, and remove entries that you've already seen.
$seen = [];
foreach(array_keys($data) as $i) {
foreach(array_keys($data[$i]) as $j) {
$id = $data[$i][$j]['id'];
if( in_array($id, $seen) ) {
unset($data[$i][$j]);
} else {
$seen[] = $id;
}
}
}
I've opted for the foreach(array_keys(...) as $x) approach as avoiding PHP references is always the sane choice.
Run it.
I am Sure That is the way which you want to get the unique array.
$unique = array_map("unserialize", array_unique(array_map("serialize", $data)));
echo "<pre>";
print_r($unique);
echo "</pre>";
I am building an array (json encoded) and returning it to the caller. My output currently looks like this:
[{"org_id":1,"org_name":"Org 1"},{"org_id":4,"org_name":"Org 4"}]
I want to add a name so that output looks like this:
{
“orgs” : [
{"org_id":1,"org_name":"Org 1"},
{"org_id":4,"org_name":"Org 4"}
]
}
Here is my current code:
// if orgs were found then
if ( is_array($orgs) && !empty($orgs) ) {
$json_orgs = json_encode($user_orgs);
// else return an empty array
} else {
$user_orgs = array();
}
I am fairly new to OO coding, so I have not figured out how to initialize an object so that "orgs" is present. Maybe I don't even need an object. Any help would be greatly appreciated.
Before you json encode the array, just wrap it in another one:
$newArray = ['orgs' => $yourCurrentArray];
Then you json encode the new variable instead.
If you rather not create a new array, you can simply do:
json_encode(['orgs' => $yourCurrentArray]);
This doesn't really have anything to do with OOP since you're just working with arrays. Associative arrays becomes objects when encoded into JSON.
You didn't say exactly how you're generating the JSON at the moment, or from what object/variable in PHP, or with what structure (there is more than one possible way).
But in general, here's how you could do it with an associative array:
$data = array (
'orgs' =>
array (
0 =>
array (
'org_id' => 1,
'org_name' => 'Org 1',
),
1 =>
array (
'org_id' => 4,
'org_name' => 'Org 4',
),
),
)
And then json_encode that to get the JSON.
(Hint: you can simply do the process in reverse to generate this example code from the desired JSON.)
You can achieve this by adding a key, for example:
// variable holding your data
$data;
// return statement in your controller
return ['orgs' => $data];
You just need to decode this with json_decode() and then you get like this
array (
0 =>
array (
'org_id' => 1,
'org_name' => 'Org 1',
),
1 =>
array (
'org_id' => 4,
'org_name' => 'Org 4',
),
)
then you need to add parant array on it
array( "orgs"=> array (
0 =>
array (
'org_id' => 1,
'org_name' => 'Org 1',
),
1 =>
array (
'org_id' => 4,
'org_name' => 'Org 4',
),
)
)
then again encode it and you will get your answer
Quite a difficult to explain, but for example i have an array:
$lol = array(
'key' => 'value',
'key_1' => 'value 1',
'simple_value',
'0' => 'lol',
'key_array' => array(
'key_in_second' => 'value_with_key_in_second',
'value_in_second_array',
)
);
After json_encode it would be
{"key":"value","key_1":"value 1","0":"lol","key_array":{"key_in_second":"value_with_key_in_second","0":"value_in_second_array"}}
So is it possible somehow detect if in php array had the key or note? In my example elements 'simple_value', '0' => 'lol' have same key.
PHP doesn't care if the number 0 is in quotes or not. It is storing it as numeric 0, same as 'value_in_second_array' will be 0, as it was the first element without a key.
Basically,
array('0'=>'lol') is the same as array(0=>'lol') is the same is array('lol');
You'll see simple_value dissappeared, as it was overwritten with lol.
The JSON accurately reflects the php. For example, if you had this code:
<?php
$lol = array(
'key' => 'value',
'key_1' => 'value 1',
'simple_value',
'0' => 'lol',
'key_array' => array(
'key_in_second' => 'value_with_key_in_second',
'value_in_second_array',
)
);
print_r($lol);
The output would be:
Array
(
[key] => value
[key_1] => value 1
[0] => lol
[key_array] => Array
(
[key_in_second] => value_with_key_in_second
[0] => value_in_second_array
)
)
What happened here is that as simple_value didn't have a key, it was assigned a key of 0, but was then overwritten with lol which came next. You can also see how the value_in_second_array was automatically assigned a key of 0.
So, nothing to do with json_encode, you just never had the data in PHP.
This question is based on my other question here about a suitable array processing algorithm.
In my case, I want to flatten a multidimensional array, but I need to store the full key to that element for reuse later.
For example :
array(
0 => array(
'label' => 'Item1',
'link' => 'http://google.com',
'children' => null
)
1 => array(
'label' => 'Item2',
'link' => 'http://google.com',
'children' => array( 3 => array(
'label' => 'SubmenuItem1',
'link' => 'http://www.yahoo.com',
'children' => null
)
)
)
2 => array(
'label' => 'Item3',
'link' => 'http://google.com',
'children' => null
)
)
Should be flattened into something like the following table
Key Link
===================================
[0] http://google.com
[1] http://google.com
[2] http://google.com
[1][3] http://yahoo.com
The problem is that I while I can easily store the location of an element in a multidimensional array, I am finding it to be quite hard to retrieve that element later. For example, if I store my key as $key = "[1][3]", I can not access it using $myarray[$key]. Is there anyway to do this?
Solution using recursion:
//Array parts should be an array containing the keys, for example, to address
//SubmenuItem1, I had 1.3 when the array was flattened. This was then exploded() to the array [1, 3]
$this->recurseIntoArray($myArray, $arrayParts);
private function recurseIntoArray(&$array, $arrayParts){
$current = $arrayParts[0];
$array[$current]['blah'] = 'blah'; //If you want to update everyone in the chain on the way down, do it here
array_shift($arrayParts);
if (!empty($arrayParts)){
$this->recurseIntoArray($array[$current]['children'], $arrayParts);
}else{
//If you want to update only the last one in the chain, do it here.
}
}
I would like to retrieve the first key from this multi-dimensional array.
Array
(
[User] => Array
(
[id] => 2
[firstname] => first
[lastname] => last
[phone] => 123-1456
[email] =>
[website] =>
[group_id] => 1
[company_id] => 1
)
)
This array is stored in $this->data.
Right now I am using key($this->data) which retrieves 'User' as it should but this doesn't feel like the correct way to reach the result.
Are there any other ways to retrieve this result?
Thanks
There are other ways of doing it but nothing as quick and as short as using key(). Every other usage is for getting all keys. For example, all of these will return the first key in an array:
$keys=array_keys($this->data);
echo $keys[0]; //prints first key
foreach ($this->data as $key => $value)
{
echo $key;
break;
}
As you can see both are sloppy.
If you want a oneliner, but you want to protect yourself from accidentally getting the wrong key if the iterator is not on the first element, try this:
reset($this->data);
reset():
reset() rewinds array 's internal
pointer to the first element and
returns the value of the first array
element.
But what you're doing looks fine to me. There is a function that does exactly what you want in one line; what else could you want?
Use this (PHP 5.5+):
echo reset(array_column($this->data, 'id'));
I had a similar problem to solve and was pleased to find this post. However, the solutions provided only works for 2 levels and do not work for a multi-dimensional array with any number of levels. I needed a solution that could work for an array with any dimension and could find the first keys of each level.
After a bit of work I found a solution that may be useful to someone else and therefore I included my solution as part of this post.
Here is a sample start array:
$myArray = array(
'referrer' => array(
'week' => array(
'201901' => array(
'Internal' => array(
'page' => array(
'number' => 201,
'visits' => 5
)
),
'External' => array(
'page' => array(
'number' => 121,
'visits' => 1
)
),
),
'201902' => array(
'Social' => array(
'page' => array(
'number' => 921,
'visits' => 100
)
),
'External' => array(
'page' => array(
'number' => 88,
'visits' => 4
)
),
)
)
)
);
As this function needs to display all the fist keys whatever the dimension of the array, this suggested a recursive function and my function looks like this:
function getFirstKeys($arr){
$keys = '';
reset($arr);
$key = key($arr);
$arr1 = $arr[$key];
if (is_array($arr1)){
$keys .= $key . '|'. getFirstKeys($arr1);
} else {
$keys = $key;
}
return $keys;
}
When the function is called using the code:
$xx = getFirstKeys($myArray);
echo '<h4>Get First Keys</h4>';
echo '<li>The keys are: '.$xx.'</li>';
the output is:
Get First Keys
The keys are: referrer|week|201901|Internal|page|number
I hope this saves someone a bit of time should they encounter a similar problem.