I'm currently building an array off of an object and I've got one element called images that has multiple sub elements called 'urls' structured like so
categories": [
{
"images": [
{
"urls": [
"path/test.jpg",
"path/test2.jpg",
"path/test3.jpg"
],
},
{
"urls": [
"path/test4.jpg",
"path/test5.jpg",
"path/test6.jpg"
],
},
{
"urls": [
"path/test7.jpg",
"path/test8.jpg",
"path/test9.jpg"
],
},
]
The values there don't have keys, it's just the url path but I'd like to add these to my $groupItem array and just have each url be it's own element on the same level as the group number (basically I'm exporting and need each url as it's own column)
The structure I want
0 =>"path/test.jpg",
1 =>"path/test2.jpg",
2 =>"path/test3.jpg"
3 =>"path/test4.jpg",
4 =>"path/test5.jpg",
5 =>"path/test6.jpg"
6 =>"path/test7.jpg",
7 =>"path/test8.jpg",
8 =>"path/test9.jpg"
The loop/array:
foreach($prices->groups as $group){
$groupItem = array();
$groupItem["number"] = $group->number;
foreach($group->images as $images){
$groupItem["urls"] = $images->urls;
}
}
How can I simply just add on any url to the groupItem level of that array?
Outside the outer loop, init the value to an empty array:
$groupItem["urls"] = [];
Then use the empty array reference operator to append new values to the end of an array:
foreach($group->images as $images){
$groupItem["urls"][] = $images->urls; // add this url to the end of the list
}
Alternatively, use array_push():
foreach($group->images as $images){
array_push($groupItem["urls"], $images->urls);
}
I think you can probably also skip the inner loop and just use the array explode operator like this:
array_push($groupItem["urls"], ...$images->urls);
You might also use array_column with (from php 5.6) a variable length argument list:
For example, for the images which contains an array of objects where each object has a property urls and contains an array of image urls:
foreach ($prices->groups as $group) {
$groupItem = array();
$groupItem["number"] = $group->number;
$groupItem= array_merge($groupItem, ...array_column($group->images, "urls"));
}
Demo
Related
I have documents stored on my server, and their information like title, filepath, date, category, etc., stored in a database. My goal is to be able to group the documents together by their categories. The document's category is stored in the database as a string like "COVID-19 | Guidance | Mortuary Affairs", and I want to convert it to an array like the following:
[
"COVID-19" => [
"Guidance"=> [
"Mortuary Affairs" => [
// Where the document info will be
]
]
]
]
The first step would be looping through the documents and exploding each category by the | delimiter:
foreach($all_documents as $document)
{
$categories = array_map('trim', explode('|', $document['category']));
}
Doing so results in the following:
[
"COVID-19",
"Guidance",
"Mortuary Affairs"
]
How would I then take this array and turn it into the nested array displayed at the top?
After the creation of the array with categories, you could iterate those categories and "drill" down a result object with a node-reference -- creating any missing properties, and then referencing them. Finally append the document to the deepest node's array (so multiple documents can end up at the same place):
$result = [];
foreach ($all_documents as $document) {
$categories = array_map('trim', explode('|', $document['category']));
$node =& $result; // reference the "root"
$last = array_pop($categories);
foreach ($categories as $category) {
if (!isset($node[$category])) $node[$category] = []; // create child
$node =& $node[$category]; // change the reference to the child
}
$node[$last][] = $document; // append document to this list
}
At the end $result will have the desired hierarchical structure.
I am trying to to pull data from an API response. but can't seem to figure out how to navigate to the "statistics" section of the response.
Here is the responce in short
{
"response": [
{
"player": {
},
"statistics": [
{
"team": {
"id": 49,
"name": "Chelsea",
"logo": "some data"
}
}
]
}
]
}
The code I have at the moment is as follows:
$leaguelist = array();
if (! empty( $desc-> response)) {
foreach ($desc->response as $players){
$player['id'] = $players->player->id;
$player['name'] = $players->player->name;
$player['first_name'] = $players->player->firstname;
$player['last_name'] = $players->player->lastname;
$player['age'] = $players->player->age;
$player['dob'] = $players->player->birth->date;
$player['pob'] = $players->player->birth->place;
$player['cob'] = $players->player->birth->country;
$player['nationality'] = $players->player->nationality;
$player['height'] = $players->player->height;
$player['weight'] = $players->player->weight;
$player['photo'] = $players->player->photo;
$player['team_logo'] = $players->statistics->team->logo;
$leaguelist[] = $player;
}
}
I am able to pull and display all data from the player directory just having problems working out the code to get onto the statistics
I have tried
$player['team_logo'] = $players->statistics->team->logo;
I can't really research much into this as I don't know what "this" is called, any help would be great as i am a hobbyist and have ran out of ideas.
Thank you in advance
Assuming that the response you show is in JSON, and you've then parsed it with json_decode, there are only two types of structure you need to know about:
Anything in [] square brackets is an array, and is accessed as numbered items [0], [1], etc; or with a foreach loop
Anything in {} curly brackets is an object, and is accessed using ->foo, etc
So working from the outside, we have:
An outer object { which you've called $desc
... from which we want key "response": $desc->response ...
Then an array [, which you've looped over: foreach ($desc->response as $players)
Then in the first item of that array, an object { which the loop assigns to $players ...
... from which we want key "statistics": $players->statistics ...
Then an array [ ...
... from which we could take the first item: $stat = $players->statistics[0]; or loop over all the items: foreach ( $players->statistics as $stat )
Each item is then an object { ...
... from which we want the "team" key: $stat->team
Which is an object { ...
... from which we want the "id" key: $stat->team->id
If we just wanted that one value, we could write it all in one go: $desc->response[0]->statistics[0]->team->id. It doesn't matter how deep we're nesting, we just need to look for the [ or { to see what to do next.
statistics is an array. So if you want an item from within it, you need to refer to an index of that array which contains the item.
E.g.
$player['team_logo'] = $players->statistics[0]->team->logo;
to get the first item.
I have a multidimensional array, consisting of products. Each sub-array has a product type. The productType is is in an array inside the Product array, such that;
0 => product [
productType [
id: 2
]
]
1 => product [
productType [
id: 1
]
]
2 => product [
productType [
id: 2
]
]
]
I need to remove an entire array element, if the id already exists, in this example, I would need to remove EITHER array[0] or array[2], it doesn't matter as I only need the productType[id] to populate the box.
I have made a loop that creates an array of the ID's that already exist, but it involves making 2 new arrays:
//This works but seems a bit inefficient
$productFinal = [];
$ids = [];
foreach ($products as $product) {
if (!in_array($product->getproductType()->getid(), $ids)) {
$productFinal[] = $product;
}
$ids[] = $product->getproductType()->getid();
}
I get the results I want, however I am sure that there is a more efficient way to do this, ideally using an inbuilt php function.
If you also get the key of each element, you could remove the element if necessary inside the foreach-loop:
$ids = [];
foreach ($products as $key => $product {
$id = $product->getproductType()->getid();
if (in_array($id, $ids)) {
unset($product[$key];
} else {
$ids[] = $id;
}
}
There is no need for a loop, you can use array_column to make the array associative, which will remove any duplicates.
Then use array_values to make the array indexed again.
$arr = array_values(array_column($arr, Null, "id"));
while ($v = $stmt - > fetch(PDO::FETCH_ASSOC)) {
$basicinfo[] = array('sysid' => $v['sysid'], 'thesis' => $v['thesis']);
}
$input = array_map("unserialize", array_unique(array_map("serialize", $basicinfo)));
echo json_encode(array_values($input), JSON_UNESCAPED_UNICODE);
}
this is how i make an array from database i want to make a multidimensional array that i can access from ajax request like data[i].group[j].leader i want to create another array inside the first array which is named thesis. I want to name that array group to represent the number of group that are taking up the subject thesis. Inside this array i want to put the value of the members of that group. I can also add another array inside the array thesis, it will be an array with same level as the array group. i have tried doing it like this
$basicinfo[$group] = array('sysid' => $v['sysid'], 'thesis' => $v['thesis'],"$group=>array('leader' => $v('leader_name'))");
I want the array to look like this
[{
"sysid": "015-08-0004-001-063-2001",
"subject": "thesis",
"group": {
"groupid": "1",
"groupleader": "John",
},
"adviser": {
"advisername": "Prof Smith",
}
}]
i want it like this so i can access each array in the ajax(jquery) like
data[i].group[j].leader
data[i].adviser[j].advisername
Update
i still need to add more table and i think more columns for now this is what i am working with
I have produced an array of fruits stored somewhere. Say it looks like this
$myFruits = array("apples"=>1, "oranges"=>3, "bananas"=>5);
This array is then passed into a function that will return json-encoded data for an API.
First, I wanted to be able to return a list of all the types of fruits I have
{"fruits":["apples", "oranges", "bananas"]}
I used this to accomplish it
echo json_encode(array("scripts" => array_keys($scripts)));
Now, I would like each type of fruit to be contained in its own hash, as such
{"fruits":
[
{name: "apples"
},
{name: "oranges"
},
{name: "bananas"
]
}
This way I can add additional fields to each fruit object without breaking existing code that may be using previous versions of this API (eg: if I decided to add the fruit counts in there as well).
Seeing how I can just create a new array and assign my list of fruits to a key called "fruits", I tried to do the same for each inner hash:
$myFruits = array("apples"=>1, "oranges"=>3, "bananas"=>5);
$data = array();
foreach ($myFruits as $key => $value) {
// initialize an associative array for each fruit
$val = array();
array_push($val, array("name" => $key));
// add it to the list of fruits
array_push($data, $val);
}
// assign list of fruits to "fruits" key
$outData = array("fruits" => $data);
echo json_encode($outData);
But I get this instead
{"fruits":[[{"name":"apples"}],[{"name":"oranges"}],[{"name":"bananas"}]]}
There are extra square braces around each fruit hash, which I assume is because I'm using an array to store each key-value pair.
How would I get my desired output?
You're close to knowing what you're doing wrong. You're creating an array, and then just using it to add one item (another array) to it.
// initialize an associative array for each fruit
$val = array(); // this guy here is unnecessary!!
array_push($val, array("name" => $key));
// add it to the list of fruits
array_push($data, $val);
Instead, just push each individual array onto $data directly like this:
array_push($data, array("name" => $key));
DEMO
You are creating an extra level in your array, simply push a new array onto $data in each iteration:
foreach ($myFruits as $key => $value) {
$data[]=array("name" => $key, "count" => $value);
}
*edited as per your comment