Get results from array by not using the key - php

I have the following code to get an array of looped posts that the user has a status of 'active'.
In that array I have multiple entries for "slug" like this.
["slug"]=>string(9) "the_bbc""
I can't pull in the data based on string number - "string(9)" as they're all different.
How can I echo "the_bbc" by searching for ["slug"] and return all results.
<?php $user_id = get_current_user_id();
$active_memberships = wc_memberships_get_user_memberships( $user_id, 'active' ); // userID and active user ?>
<pre><?php var_dump ($active_memberships, $product_id); ?></pre>
Yes this looks quite novice and have been told yesterday by another person but I'm in my first year in college studying php.
Thanks

If you have multiple "slug" in an array you can loop through it with a foreach(), ex:
foreach ( $active_memberships['slug'] as $slug) {
//do whatever with this variable
}
I hope that I understood you correctly. Please provide a better description next time.

Related

ACF make top 10 based on field value

I'm using ACF for a while now and I thought this would be easier but cant figure out how to do this properly...
I'm trying to create some kind of trophy cabinet. So every company has a score that is stored inside a ACF called "company_score".
For example we have companies called Microsoft, Facebook and Twitter. They all have a score:
Facebook = 200000
Microsoft = 900000
Twitter = 100000
So the top 3 wil be like
1) Microsoft
2) Facebook
3) Twitter
I know how to display the value of an ACF but how can I compare all the scores that are stored and when a company has the best score it will display a gold medal. When a company has the second best score it will display a silver medal and so on.
I all had it figured it out in my head but a bit stuck here how to do this.
There could be several approaches to handle this. The first one, which comes in my mind is very simple.
Try these steps:
Pull all fields
Store in an array
Sort the array in ascending order
Display the results.
I hope, you've some understanding of the code but here are the coded guidelines...
<?php
$fields = get_fields();
$company_details = array();
if( $fields ):
foreach( $fields as $name => $value ):
$company_details[ $name ] = $value;
endforeach;
endif;
//to sort by company score
arsort( $company_details );
//loop through the array and display results, like
foreach( $company_details as $name => $value):
echo "Company name is: " .$name. ". Company Score: " . $value;
endforeach;
PS: The code is not tested because the purpose was to share logic with you. So, ignore if there's any error.

Matching a string with an array key

I'm trying how to figure something out for my website.
This is not my code just an example to make it easier to understand what i mean.
Lets say i have an array like this:
$services = array(
Marketing => marketing:342343423423,
Sales => sales:779876786,
)
And i have a form on my website. I can get the posted values with a POST request.
The POST request can for example look like this
$_POST['service_request']
Now what i want to know is how to do the next:
if $_POST['service_request'] matches one of the array keys inside $services then print the relevant value of this array key.
So lets say an user fills my form, and his service request is marketing then i want to check if this service request exists inside the $service variable and if it exist print the value.
use key_exists function of php.
if(key_exists($_POST['service_request'],$services)){
//exists, perform rest of the logic here.
}
Update: it's an alias of array_key_exists so both are basically same.
Edit:
Code below can give an exception if the key isn't set. You should use the key_exists, given in the other answer. Or change it to:
if ( isset($services[$_POST['service_request']]) ) {
echo $services[$_POST['service_request']];
}
This code will print the value from the array with the given key:
$value = $services[$_POST['service_request']];
echo (isset($value) ? $value : '');

Strange variable overwrite in foreach loop

This must be something ugly obvious, but I'm stucked on this and can't solve it for past two hours.
I have this piece of code:
foreach($idMap as $menuId=>$pageId)
{
echo('$this->update("menus_items", SET "link = /content/show?id='.$pageId.'" WHERE id = '.$menuId.');'."\n");
$this->update
(
'menus_items',
array('link'=>'/content/show?id='.$pageId),
array('id = '.$menuId)
);
}
echo part works as expected ($pageId is different for each item, taken from $idMap), while Yii's CDbCommand::update() gets wako and have $pageId equal to it's last value for all loop iterations.
In other words, if I have 20 menu items and last item in result set has pageId = 18, then when using CDbCommand::update(), I'm getting all menu items set to that last value.
There must be some variable overwriting here, but I can't find it for past two hours, especially, that echo put just one line above works great. Can someone help here.
Guessing, but does $this->update() expect a single array for its bind arguments?
$this->update
(
'menus_items',
array(
'link' => '/content/show?id='.$pageId,
'id' => $menuId
)
);

How can I group by column value in a yii query?

I have a data table with 7 columns and 400 records. One of them is budget. I want to group the 400 rows by budget so that I get an array like this:
[budget]=>array(
[0]=>array(
[column1]=>'1',
[column2]=>'sand'
),
[1]=>array(
[column1]=>'2',
[column2]=>'clay'
)
)
[budget2]=>array(
[0]=>array(
[column1]=>'3',
[column2]=>'silt'
),
[1]=>array(
[column1]=>'4',
[column2]=>'stone'
)
)
So far I have been playing around with Yii's CdbCommand and CdbDataReader and PHP's PDOStatement but nothing is working right. I tried the following code
public function actionBidCostByBudget(){
$command = Yii::app()->db
->createCommand()
->Select('*')
->From('bid_cost')
# ->Query()
;
echo '<pre>';
echo get_class($command);
$pdostatement=$command->getPdoStatement();
if($pdostatement) echo get_class($pdostatement);
# print_r($statement->fetchall(PDO::FETCH_COLUMN|PDO::FETCH_GROUP));
# print_r($command->readall());
# print_r($statement->fetch());
# $columnsArray = BidCost::attributeLabels();
//print_r($rowsArray);
//$this->layout='\\layout';
}
The attempts to print_r all print out with nothing. getPdoStatement equals nothing. I have been trying to use PDO::FETCH_COLUMN|PDO::FETCH_GROUP as per the Php.net website, but it does not work either because I get nothing.
One of Yii's strengths is it's ActiveRecord, so why not use it?
Make your budget to a separate table (so you can generate a model from it). Reference it from your "datatable".
CREATE TABLE budget (
id INTEGER PRIMARY KEY,
name TEXT
);
CREATE TABLE datatable(
column1 TEXT,
column2 TEXT,
...
budget_id INTEGER,
FOREIGN KEY(budget_id) REFERENCES budget(id)
);
Next generate models with Gii, and now you can use your newly made relations like this:
$budget = Budget::model()->findByAttributes( ["name"=>"budget2"] );
foreach( $budget->datatables as $dt ) {
echo $dt->column1;
echo $dt->column2;
}
(I know. Not the array you asked for. Sorry if I'm way off with this.)
Alright, the bottom line is that I was not able to find a way to do this right thru Yii, so I did it with a more hands-on approach.
The first thing I did was basically initiate a database connection thru Yii.
$command = Yii::app()->db //outputs CDbConnnection
The next thing I did was get a PDO class from the connection:
$pdoinstance = $command->getPdoInstance(); //outputs PDO class
From this point, it was help obtained from PHP.net and another question posted on this forum:
$pdostatement=$pdoinstance->prepare('SELECT BUDGET_CODE,
PAY_ITEM, ITEM, DESCRIPTION FROM bidcost');
$pdostatement->execute();
//default fetch mode could not be set
# $pdostatement->setfetchmode(PDO::FETCH_GROUP|PDO::FETCH_ASSOC);
//returns array
$testarray=$pdostatement->fetchAll(PDO::FETCH_GROUP|PDO::FETCH_ASSOC);

I need to get the post id for the first post of the current user in wordpress

I have this so far
get_currentuserinfo(); $the_post = get_posts("author=" . $current_user->ID . "&posts_per_page=1"); $the_post = $the_post[0];
but I'm not sure how to get just the ID out of the array
get_posts() will return an array of posts ordered by the date of publication, in descending order. So, with the code you posted, the first post in the array ([0]) will be the last post published by the author. If you really want the first post of the user, you can just add the order argument to the call (&order=ASC) to override the default.
I think the key for the ID is just "ID", so you can retrieve it with $the_post = $post[0]['ID']. But I have to admit I can't remember for sure and the documentation does not detail that, it could also be "post_id". You can do a: print_r($the_post) to check the keys of the returned array.
You can write query like this way-
$oldest_post_query = get_posts("post_type=post&numberposts=1&order=ASC");
$oldest_post_id = $oldest_post_query[0]->ID;
//print the post title
<h1>'.get_the_title( $oldest_post_id ).'</h1>';

Categories