Store multiple different dynamcially added items into array - php

I am trying to create an array when im using TMDB(The movie database) API, I am using this wrapper for PHP.
I am trying to do this
require_once('../classes/tmdb-api.php');
// if you have no $conf it uses the default config
$tmdb = new TMDB();
//Insert your API Key of TMDB
//Necessary if you use default conf
$tmdb->setAPIKey('myKEy');
//Title to search for
$title = $_POST['searchTerm'];
$movies = $tmdb->searchMovie($title);
// returns an array of Movie Object
$movieArray = array();
$movieSearchArray = array();
foreach($movies as $movie) {
$movieTitle = $movie->getTitle();
$movieSearchArray[$movieTitle] = ['ID'][$movie->getID()];
$movieSearchArray[$movieTitle] = ['Trailer'][$movie->getTrailer()];
}
$movieArray[] = $movieSearchArray;
print_r($movieArray);
So for example when a user searches 'Rocky' It will bring back multiple different movie titles but for each of the movie titles I want to create an array like this for example, I am trying to do this in the foreach loop but what am i doing wrong?
[Rocky] => (
"id" = "2",
"rating" = "4"
)
Keep in mind that there could be 10s of different movies. This is what i get returned when I search 'Rocky' right now.
Array
(
[0] => Array
(
[Rocky] =>
[Rocky II] =>
[Rocky IV] =>
[Rocky V] =>
[Rocky Balboa] =>
[Rocky III] =>
[Rocky VI] =>
[Creed] =>
[The Real Rocky] =>
[Rocky Marciano] =>
[Where is Rocky II?] =>
[Rocky Handsome] =>
[Rocky Road] =>
[Rocky Mountain] =>
[Rocky Pink] =>
[Rocky and Bullwinkle] =>
[The Rocky Horror Picture Show] =>
[Rocky Mountain Grandeur] =>
)
)

I guess you can do that, with only exception of assigning item to an array, indices in [] must be before equal (=) sign, or you have to assign whole array with keys and values.
so either
foreach($movies as $movie) {
$movieTitle = $movie->getTitle();
$movieSearchArray[$movieTitle]['ID'] = $movie->getID();
$movieSearchArray[$movieTitle]['Trailer'] = $movie->getTrailer();
}
or
foreach($movies as $movie) {
$movieSearchArray[$movie->getTitle()] = array(
'ID' => $movie->getID(),
'Trailer' => $movie->getTrailer()
);
}
and so on for other data in the $movie object

Related

Loop over query and add each item as associative array in one multi-dimensional array

I would like to loop over records, retrieve multiple properties and values for each item and then keep pushing each item as an associative array using name/value pairs into one large multidimensional array .
For example, in my loop I have 2 records, but my associate arrays keep getting written over. How can I just push associate arrays.
My code is only returning one key, although it should return two.
PHP
// loop over wordpress posts
while ( have_posts() ) : the_post();
$propertytype = get_field('PropertyType');
$propertyname = get_field('PropertyName');
$propertylocation = get_field('PropertyLocation');
$propertydescr = get_field('PropertyDescription');
$propertydphone = get_field('PropertyPhone');
$propertywebsite = get_field('PropertyWebsite');
$propertystatus = get_field('PropertyStatus');
$propertythumb = get_field('PropertyThumbnail');
$propertylargeimage = get_field('PropertyLargeImage');
//add each record as an associative array
$data1 = array(
'PropertyType' => $propertytype,
'PropertyName' => $propertyname,
'PropertyLocation' => $propertylocation,
'PropertyDescription' => $propertydescr,
'PropertyPhone' => $propertydphone,
'PropertyWebsite' => $propertywebsite,
'PropertyStatus' => $propertystatus,
'PropertyThumbnail' => $propertythumb,
'PropertyLargeImage' => $propertylargeimage
);
endwhile;
Define $data1 as array before you start the loop
$data1[] = []; // or array() for backwards compatibility
inside the loop
$data1[] = array(
'PropertyType' => $propertytype,
'PropertyName' => $propertyname,
'PropertyLocation' => $propertylocation,
'PropertyDescription' => $propertydescr,
'PropertyPhone' => $propertydphone,
'PropertyWebsite' => $propertywebsite,
'PropertyStatus' => $propertystatus,
'PropertyThumbnail' => $propertythumb,
'PropertyLargeImage' => $propertylargeimage
);

PHP: create subarray based on similar value types

Hello to the community: in the following array, I'd like to gather all the hobbies of the same user under that user's name into a subarray I'd call hobbies.
My current solution is to compare whether the email value is the same for both arrays, and if so, then push the hobby into its own array.
The problem is that the loops seems right but does not produce the results I expect it and I can't see where lies the problem. I thank you all for your time.
for($x = 0; $x <= count($majorArray); $x++) {
if($majorArray[$x]['email'] == $majorArray[$x+1]['email'])
array_push($hobbies, $majorArray[$x]['hobby']);
}
The array:
Array
(
[1] => Array
(
[fname] => Eli
[lname] => Solo
[hobby] => plants
[id] => 1
[email] => elis#elis.com
)
[2] => Array
(
[fname] => Eli
[lname] => Solo
[hobby] => hiking
[id] => 1
[email] => elis#elis.com
)
The problem with your code is that you compare the email of the current contents with the email of the next.
This check does not check if the user is already present, it just checks the next user in the array. This will only work if the next user is also the current, not if there is something in between.
Also, this code will eventually give you an undefined index error, as it will try to fetch the data under the next key in the last iteration.
Also it's not clear where $hobbies is from, according to you explanation, you want to create a hobbies array, and append all data there.
You can try the following (untested):
<?php
$majorArray = [
[
'fname' => 'Eli',
'lname' => 'Solo',
'hobby' => 'plants',
'id' => 1,
'email' => 'elis#elis.com',
],
[
'fname' => 'Eli',
'lname' => 'Solo',
'hobby' => 'hiking',
'id' => 1,
'email' => 'elis#elis.com',
],
];
$output = [];
foreach ($majorArray as $userData) {
// check if email already exists as key, you can also just use id for this
if (!array_key_exists($userData['email'], $output)) {
$newUserData = [
'fname' => $userData['fname'],
'lname' => $userData['lname'],
'id' => $userData['id'],
'email' => $userData['email'],
'hobbies' => [], // create the hobbies array
];
// add the newly created user data array to the output with email as key
$output[$userData['email']] = $newUserData;
}
// append the hobby to the hobbies array
$output[$userData['email']]['hobbies'][] = $userData['hobby'];
}
// array_values will reset the array keys if you need to
print_r(array_values($output));
Simply write a new array and use the ID as key
$betterArray = array();
foreach($majorArray as $data){
$betterArray[$data['id']]['fname'] = $data['fname'];
$betterArray[$data['id']]['lname'] = $data['lname'];
$betterArray[$data['id']]['email'] = $data['email'];
$betterArray[$data['id']]['hobbies'][] = $data['hobby'];
}
notice the [] in the last line in the loop to add a new element to the subarray each time it loops trough

Looping through a multi-dimentional array in php

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;
}

Push array into an array using array_push

I have four elements of data stored in variables.
I wish to create a multi-dimensional array.
Firstly, I wish the ID to be the main key for the array. And within the ID key, I wish to store description, image_med and image_full
I have started by initialising an array and pushing the ID:
$image_id = $image['id'];
$this_image = array();
array_push($this_image, $image_id);
The result is:
array(1) {
[0]=>
int(2161)
}
Now I wish to push three more elements into this ID array. I'd like to create something like the following:
array(1) {
['ID']=>
int(2161)
array(3){
['description'] => string(Description goes here),
['medium'] => string(http://www.blah.com/12345),
['full'] => string(http://www.blah.com/67890)
}
}
So first of all the parent key is called ID not just [0]
And secondly that the following three variables are added with their keys:
description ($image_desc is the variable)
medium ($image_med is the variable)
full ($image_full is the variable)
How would I do this?
Let $id be the id of the image:
$array=array();
//then you can use this code in a loop:
$array[$id]=array(
'description'=>$image_desc,
'medium'=>$image_med,
'full'=> image_full
);
There is no need to use array_push function, actually array_push has a little worse performance because of function call's overhead (this is an advanced topic, anyway)
is that what you are looking for ?
$images = array(); // an array of all images
$image_id = $image['id'];
$images[$image_id] = array(
'ID' => $image_id, // optional, would be repeating id you already have
'description' => "Blabla",
'medium' => "Blabla",
'full' => "Blabla",
);
You would do that automatically in a loop I suppose thought... And if you dont need the ID as "key", what about:
$images = array();
$image1 = array(
'ID' => $image_id,
'description' => "Blabla",
'medium' => "Blabla",
'full' => "Blabla",
);
array_push($images, $image1);
Not sure what you are looking to achieve though.
Your question is not very clear. What you probably need could be something like this:
// Create a list (of images)
$listImages = array();
// Information about an image (it can be constructed as displayed here,
// retrieved from a database or from other source)
$image = array(
'id' => 123,
'description' => 'Nice kitty',
'medium' => 'http://www.blah.com/12345',
'full' => 'http://www.blah.com/67890',
);
// Extract the ID of the image into a variable (this is for code clarity)
$imageId = $image['id'];
// Store the image in the list, indexed by image ID
$listImages[$imageId] = $image;
// Get/create another image...
$image = array(
'id' => 456,
'description' => 'another kitty',
// ... other fields here
);
// ... put it into the list (skip the helper variable $imageId)
$listImages[$image['id']] = $image;
This is how the output of print_r($listImages) looks like:
Array
(
[123] => Array
(
[id] => 123
[description] => Nice kitty
[medium] => http://www.blah.com/12345
[full] => http://www.blah.com/67890
)
[456] => Array
(
[id] => 456
[description] => another kitty
)
)

PHP ObjectId group a number of Ids

I have a two collections one of all the people I am following and another of what they have been posting on social networking sites like Twitter and Facebook.
The following collection has a subarray of the _id of the feed collection of each user which each status has the word owner and that has the ObjectId that the owner which is the same as the following key. Here is an example.
'_id' => new MongoId("REMOVED"),
'following' =>
array (
'0' => 'ObjectId("53bf464ee7fda8780c8b4568")',
'1' => 'ObjectId("53b00ab5e7fda8304b8b4567")',
),
'owner' => new MongoId("53b9ea3ae7fda8863c8b4123"),
and in the feed you will see that the following.0 status below
array (
'_id' => new MongoId("REMOVED"),
'owner' => new MongoId("53bf464ee7fda8780c8b4568"),
'status' => ' love this video - Pedigree Shelter dogs http://youtube.com/watch?v=5v5Ui8HUuN8',
'timestamp' => new MongoDate(1405044327, 565000),
)
While I can loop through one by one, I can't for some reason do an $or search. I am not quite understanding how I loop through the following array and add it to the search query before I ran the query.
collection = static::db()->feed;
$where=array( '$or' => array(array('owner' => new MongoId($following.0)))));
$feed = $collection->find($where);
return $feed;
now I understand I will somehow have to loop the $where=array( '$or' => array(array('owner' => new MongoId($following.0))))); But I am just not 100% sure how to do this.
Update
As per the answer below I had to edit the array that was returned - now I have only got this working manually and can't seem to get the PHP script to do it.
Answer Returns
Array ( [owner] => Array ( [$in] => Array ( [0] => new MongoId("53bf464ee7fda8780c8b4568") [1] => new MongoId("53b00ab5e7fda8304b8b4567") ) ) )
Correct:
Array ( "owner" => Array ( '$in' => Array ( "0" => new MongoId("53bf464ee7fda8780c8b4568"), "1" => new MongoId("53b00ab5e7fda8304b8b4567") ) ) )
I am not sure how else to get this to work.
current PHP
$collection = static::db()->following;
$following = $collection->findOne(array ('owner' => new MongoId($_SESSION['user_information'][0]['_id'])));
$follow = $following['following'];
$collection = static::db()->feed;
$where=array("owner" => array( '$in' =>$follow));
print_r($where);
$feed = $collection->find($where);
print_r($feed);
return $feed;
I have fixed a small issue with the collection and now the return array shows
Array ( [owner] => Array ( [$in] => Array ( [0] => MongoId Object ( [$id] => 53bf464ee7fda8780c8b4568 ) [1] => MongoId Object ( [$id] => 53b00ab5e7fda8304b8b4567 ) ) ) )
However, I still can't get it to return the feed like this one:
array (
'_id' => new MongoId("53bf4667e7fda8700e8b4567"),
'owner' => new MongoId("53bf464ee7fda8780c8b4568"),
'status' => ' love this video - Pedigree Shelter dogs http://youtube.com/watch?v=5v5Ui8HUuN8',
'timestamp' => new MongoDate(1405044327, 565000),
)
I am presuming here that this is just a PHPism in the way things are displayed and that your following array is an actual array and not a hash/map, which would generally look like this in a JSON representation:
{
"following": [
ObjectId("53bf464ee7fda8780c8b4568"),
ObjectId("53b00ab5e7fda8304b8b4567"),
],
"owner": ObjectId("53b9ea3ae7fda8863c8b4123"),
}
In which case the "following" is already an actual array, and if you just want to .find() all the "feed" items for the people you are following, then you just pass that to the $in operator for your query selection:
$where = array( "owner" => array( '$in' => $following ) );
$feed = $collection->find($where);
return $feed;
The returned cursor will only contain results from the feed where the "owner" is present in your "following" array from the other collection item.
Watch this code:
$list = array(new MongoId(), new MongoId, new MongoId());
$doc = array( "owner" => array( '$in' => $list ));
echo json_encode( $doc, JSON_PRETTY_PRINT );
Despite how this serializes for JSON by this method the equivalent JSON is:
{
"owner": {
"$in": [
ObjectId("53bf8157c8b5e635068b4567"),
ObjectId("53bf8157c8b5e635068b4568"),
ObjectId("53bf8157c8b5e635068b4569")
]
}
}
That is how the BSON will serialize and is the correct query.
(Answer added on behalf the question author to move it to the answer space).
The issue was fixed when I used the following:
var_dump(iterator_to_array($feed));

Categories