I want to make a dictionary (or list) that is a subset of another dictionary in PHP. Please look below at my code written in Python:
ThePythons = {
'GC': 'Graham Chapman',
'JC': 'John Cleese',
'EI': 'Eric Idle',
'MP': 'Michael Palin'
}
query = ['EI', 'JC']
output = [[item,ThePythons[item]] for item in query if item in ThePythons]
print(output)
And output is:
[['EI', 'Eric Idle'], ['JC', 'John Cleese']]
I don't know how to accomplish the same functionality in in PHP. Please give me the corresponding code in PHP. Many thanks in advance!
The following should work:
<?php
$thePythons = array(
'GC' => 'Graham Chapman',
'JC' => 'John Cleese',
'EI' => 'Eric Idle',
'MP' => 'Michael Palin'
);
$query = array(0 => 'EI', 1 => 'JC');
$resultList = array();
for ($i=0; $i<sizeof($query); $i++) {
$resultList[$i] = array($query[$i] => $thePythons[$query[$i]]);
}
var_dump($resultList);
?>
Output
array(2) {
[0]=>
array(1) {
["EI"]=>
string(9) "Eric Idle"
}
[1]=>
array(1) {
["JC"]=>
string(11) "John Cleese"
}
}
Related
I have a database and a table user. when i perform below code i got output as below.
$searchQuery = array('userID' => '2');
$collection = $db->mydatabase->users;
$cursor = $collection->find()->limit(2);
foreach ($cursor as $doc) {
var_dump($doc);
}
Output:
array(4) {
'_id' =>
class MongoId#8 (1) {
public $$id =>
string(24) "56c8216d7f8b9a0e148b4567"
}
'userID' =>
int(7)
'lastTimeOnline' =>
string(19) "2016-02-20 01:48:53"
'displayName' =>
string(0) ""
}
array(4) {
'_id' =>
class MongoId#9 (1) {
public $$id =>
string(24) "56c8216d7f8b9a0e148b4568"
}
'userID' =>
int(2)
'lastTimeOnline' =>
string(19) "2016-02-20 01:48:53"
'displayName' =>
string(0) ""
}
Now i need to find only those records whose userID is 2, so i change the code as below.
$searchQuery = array('userID' => '2');
$collection = $db->mydatabase->users;
$cursor = $collection->find($searchQuery)->limit(2);
foreach ($cursor as $doc) {
var_dump($doc);
}
but now the output is blank :-(
I have two doubts.
A) why 2nd code to fetch userId=2 is not working
B)why on both cases var_dump($cursor) is giving below output and why not detail of $doc
class MongoCursor#5 (0) {
}
Seems like the userID in database is saved as Integer and your are trying to query using a string parameter, try to change the query array to the following:
$searchQuery = array('userID' => 2);
You are storing the userId as an integer and in the query you are using a string due to which you are find nothing so instead of writing 2 like this '2' write it like this 2
I'm trying to get an array to output in a key and value format. When I use the second style shown below it works fine, but when I use the first style I don't get the same results. I think something is different in how the keys are used but I'm not entirely sure.
So, is there any difference between building an array like this:
$featured = get_post_meta($profileID, 'profile_featured', true);
if ($featured == '1'){$my_fake_pages["featured"] = "Featured";};
$celebs = get_post_meta($profileID, 'profile_celebs', true);
if ($celebs== '1'){$my_fake_pages["coversandcelebrities"] = "Covers & Celebrities";};
$fashion = get_post_meta($profileID, 'profile_fashion', true);
if ($fashion == '1'){$my_fake_pages["fashion"] = "Fashion";};
$beauty = get_post_meta($profileID, 'profile_beauty', true);
if ($beauty == '1'){$my_fake_pages["beauty"] = "Beauty";};
$advertising = get_post_meta($profileID, 'profile_advertising', true);
if ($advertising == '1'){$my_fake_pages["advertising"] = "Advertising";};
$bio = get_post_meta($profileID, 'profile_bio', true);
if ($bio == '1'){$my_fake_pages["bio"] = "Bio";};
and writing one like this:
$my_fake_pages = array(
'featured' => 'Featured',
'coversandcelebrities' => 'Covers & Celebrities',
'fashion' => 'Fashion',
'beauty' => 'Beauty',
'advertising' => 'Advertising',
'bio' => 'Bio'
);
Thanks in advance.
** To be clear, I know one is conditional and the other isn't. What I'm wanting to know is if the output style of the first example is equivalent to that of the second, where the key is the index of the array rather than a number being the index, and the value is still the value.
They are the same. To prove it, I've simplified your code and compared the two generated arrays
<?php
$a["featured"] = "Featured";
$a["coversandcelebrities"] = "Covers & Celebrities";
$a["fashion"] = "Fashion";
$a["beauty"] = "Beauty";
$a["advertising"] = "Advertising";
$a["bio"] = "Bio";
$b = array(
'featured' => 'Featured',
'coversandcelebrities' => 'Covers & Celebrities',
'fashion' => 'Fashion',
'beauty' => 'Beauty',
'advertising' => 'Advertising',
'bio' => 'Bio'
);
$same = !array_diff($a, $b) && !array_diff($b, $a);
var_dump($a);
var_dump($b);
echo "<br>Same = $same";
This outputs:
array(6) { ["featured"]=> string(8) "Featured" ["coversandcelebrities"]=> string(24) "Covers & Celebrities" ["fashion"]=> string(7) "Fashion" ["beauty"]=> string(6) "Beauty" ["advertising"]=> string(11) "Advertising" ["bio"]=> string(3) "Bio" }
array(6) { ["featured"]=> string(8) "Featured" ["coversandcelebrities"]=> string(24) "Covers & Celebrities" ["fashion"]=> string(7) "Fashion" ["beauty"]=> string(6) "Beauty" ["advertising"]=> string(11) "Advertising" ["bio"]=> string(3) "Bio" }
Same = 1
The if() version only adds to the array if the conditions are met. the second one adds everything, unconditionally. that has nothing to do with the keys.
It's the difference between going to the grocery store with a shopping list and only getting what's on the list, and going to the store and buying 1 of everything.
If i understand your question right, you want to know if building an array like this:
$my_fake_pages["featured"] = "Featured";
$my_fake_pages["coversandcelebrities"] = "Covers & Celebrities";
$my_fake_pages["fashion"] = "Fashion";
$my_fake_pages["beauty"] = "Beauty";
$my_fake_pages["advertising"] = "Advertising";
$my_fake_pages["bio"] = "Bio";
is any different than building it like this:
$my_fake_pages = array(
'featured' => 'Featured',
'coversandcelebrities' => 'Covers & Celebrities',
'fashion' => 'Fashion',
'beauty' => 'Beauty',
'advertising' => 'Advertising',
'bio' => 'Bio'
);
The answer is no. Both generate an associative array (instead of a numbered array) like this:
array(6) {
["featured"]=>
string(8) "Featured"
["coversandcelebrities"]=>
string(24) "Covers & Celebrities"
["fashion"]=>
string(7) "Fashion"
["beauty"]=>
string(6) "Beauty"
["advertising"]=>
string(11) "Advertising"
["bio"]=>
string(3) "Bio"
}
And also since PHP 5.4.x you can have a "short syntax" array generation like this (notice the []):
$my_fake_pages = [
'featured' => 'Featured',
'coversandcelebrities' => 'Covers & Celebrities',
'fashion' => 'Fashion',
'beauty' => 'Beauty',
'advertising' => 'Advertising',
'bio' => 'Bio'
];
** To be clear, I know one is conditional and the other isn't. What I'm wanting to know is if the output style of the first example is equivalent to that of the second, where the key is the index of the array rather than a number being the index, and the value is still the value.
Yes, if all conditions evaluate as true, then the array format is exactly the same. Both will be associative arrays with the same key
I am trying to fetch some data from an API and put it into an array and then to MySQL.
My Code:
$find_sql = "SELECT * FROM `scrape`";
$users_to_scrape = $app['db']->fetchAll($find_sql);
$instagram = $app['instagram'];
$oauth = json_decode(file_get_contents($app['oauth_path']));
$instagram->setAccessToken($oauth);
foreach($users_to_scrape as $user_to_scrape) {
printf("Getting info for %s <%s>\n", $user_to_scrape['instagram_id'], $user_to_scrape['user_name']);
$follows = $instagram->getUser($user_to_scrape['instagram_id'], 999);
foreach($follows->data as $follow) {
echo var_dump($follows);
$data = array(
'instagram_id' => $follow->id,
'followed_by_instgram_id' => $user_to_scrape['instagram_id'],
'user_name' => $follow->username,
'full_name' => iconv('UTF-8', 'UTF-8//IGNORE', utf8_encode($follow->full_name)),
'profile_picture' => $follow->profile_picture,
'followers' => $follow->counts->followed_by,
'follows' => $follow->counts->follows
);
printf("+ %s <%s>\n", $data['instagram_id'], $data['user_name']);
//skapa tabell med follows (instagram_id,
if ($follow->counts->followed_by >= "30000") {
$app['db']->insert('follows', $data);
}
}
}
The Vardump returns this:
object(stdClass)#111 (2) {
["meta"]=>
object(stdClass)#112 (1) {
["code"]=>
int(200)
}
["data"]=>
object(stdClass)#113 (7) {
["username"]=>
string(9) "Dimbos"
["bio"]=>
string(97) "•Have fun in life Contact: info#skogen.com"
["website"]=>
string(24) "http://www.life.com"
["profile_picture"]=>
string(106) "https://xxertt.com/hphotos-ak-xaf1/t51.2885-19/11311351_362556250614181_543_a.jpg"
["full_name"]=>
string(10) "Dimbo"
["counts"]=>
object(stdClass)#114 (3) {
["media"]=>
int(113)
["followed_by"]=>
int(256673)
["follows"]=>
int(345)
}
["id"]=>
string(8) "38353560"
}
}
And the error I receive is this:
Notice: Trying to get property of non-object in /var/www/script.php on line 40
On line 40 we have this:
'instagram_id' => $follow->id,
I also get error on the following set arrays.
Can't really figure it out.
Because $follows->data is a stdClass object, iterating it with foreach will loop over each of its properties individually, returning the value of each property. This means that though id is present in the loop, it is merely the last data element of the loop, inaccessible by its property name.
Using the foreach, the iterator value of $follow results directly in the values rather than properties, as in:
// Value of $follow on each loop iteration:
"Dimbos"
"•Have fun in life Contact: info#skogen.com"
"http://www.life.com"
// etc...
You don't need the foreach loop. Instead, access each element of $follows->data directly:
// Remove the foreach loop
$data = array(
// Each property is directly accessible in $follows->data
'instagram_id' => $follows->data->id,
'followed_by_instgram_id' => $user_to_scrape['instagram_id'],
'user_name' => $follows->data->username,
'full_name' => iconv('UTF-8', 'UTF-8//IGNORE', utf8_encode($follows->data->full_name)),
'profile_picture' => $follows->data->profile_picture,
'followers' => $follows->data->counts->followed_by,
'follows' => $follows->data->counts->follows
);
printf("+ %s <%s>\n", $data['instagram_id'], $data['user_name']);
//skapa tabell med follows (instagram_id,
if ($follows->data->counts->followed_by >= "30000") {
$app['db']->insert('follows', $data);
}
You could create a variable that references the data property, allowing you to access those inner properties with less code, but I don't see it as necessary.
// Refer to data in $follow
$follow = $follows->data;
echo $follow->id;
echo $follow->counts->followed_by;
// etc...
Here is the example PHP array representation
array(
"test1" => array(
"test1subtest1" => array(..)
),
"test2" => array(
"test2subtest1" => array(..)
)
)
So, here is the question: is there any tool in PHP which can be used to assign values to multidimensional array with random depth and index names? It suppose to look like this:
$valuetoassing = "TESTVALUE";
$testarray = array();
array_assign_multidimensional($testarray, $valuetoassing, array("test1", "test1subtest1", "test1subtest1subtest1"));
Problem is that I do not know what depth the array will have, so I can not code it. Index names are also generated at the run time.
EDIT: I figured that my particular case can be solved using some kind of linked list (stored as array with items that contain actual data and pointer to the index of the next element), but I'm sure I'll meet this problem again in the future so I will not close the question right now.
This is pretty easy to do using references.
function array_assign_multidimensional(&$input_array, $value, $list){
$assignee = &$input_array;
foreach($list as $key){
$assignee = &$assignee[$key];
}
$assignee = $value;
}
$input = array(
'firstLayer' => array(
'secondLayer' => array(
'test' => 'old'
)
),
'randomOutlyingValue' => ''
);
array_assign_multidimensional($input, 'new', array('firstLayer', 'secondLayer', 'test'));
var_dump($input);
/*
array(2) {
["firstLayer"]=>
array(1) {
["secondLayer"]=>
array(1) {
["test"]=>
string(3) "new"
}
}
["randomOutlyingValue"]=>
string(0) ""
}
*/
I am using XMLRPC to build an XML structure that passes across product information to a 3rd party system. I need to build an associative array of the product custom options and I don't know what syntax to use as the value in each case is an object.
I can't debug and play about with it as I normally would as believe it or not I've had to do this on a live site so I've been emailing myself the array to make sure it looks alright, then when it does I've applied it to the site, XMLRPC throws an error saying it can't serialize the object I've built, then I quickly switch it back out again.
If I hardcode it like this it works fine.
$item_array = array(
"product_id" => new xmlrpcval($item->getSku()),
"name" => new xmlrpcval($item->getName()),
"price" => new xmlrpcval($item->getBaseCalculationPrice(), 'double'),
"vat_inclusive" => new xmlrpcval(0,'int'),
"quantity" => new xmlrpcval($item->getQty(),'int'),
"option_text" => new xmlrpcval(
array(
"option_1" => new xmlrpcval("Colour: Military Black"),
"option_2" => new xmlrpcval("Sizes: L")
),
"struct")
);
It's the folowing section I need to generate, specifically the array in a foreach loop as I don't know how many options there will be;
"option_text" => new xmlrpcval(
array(
"option_1" => new xmlrpcval("Colour: Military Black"),
"option_2" => new xmlrpcval("Sizes: L")
),
"struct")
If I do it like below then it comes out fine, but the value is a string rather than an object, which XMLRPC can't serialize;
$optioncount = 1;
$attList = array();
foreach ( $attributes as $attribute => $value ) {
$attpair = implode(": ", $value);
$attList['option_'. $optioncount] = 'new xmlrpcval("'.$attpair.'")';
$optioncount++;
}
If I var_dump($attList) I get;
array(2) {
["option_1"]=>
string(39) "new xmlrpcval("Colour: Military Black")"
["option_2"]=>
string(25) "new xmlrpcval("Sizes: L")"
}
Any other way seems to turn $attList into a total mess - I know this should be very basic but for the life of my I can't get this working. Thanks for any pointers.
If I var_dump($attList) when I use new xmlrpcval($attpair); I get;
array(2) {
["option_1"]=>
object(xmlrpcval)#469 (3) {
["me"]=>
array(1) {
["string"]=>
string(22) "Colour: Military Black"
}
["mytype"]=>
int(1)
["_php_class"]=>
NULL
}
["option_2"]=>
object(xmlrpcval)#433 (3) {
["me"]=>
array(1) {
["string"]=>
string(8) "Sizes: L"
}
["mytype"]=>
int(1)
["_php_class"]=>
NULL
}
}
Building your array must look like:
$optioncount = 1;
$attList = array();
foreach ( $attributes as $attribute => $value ) {
$attpair = implode(": ", $value);
$attList['option_'. $optioncount] = new xmlrpcval($attpair);
$optioncount++;
}
And then:
"option_text" => new xmlrpcval(
$attList,
"struct")