So I have two methods inside my class that are using the same foreach and they're being repeated within both methods .. Is there a best way to define foreach inside its own method? So I'd like to have the foreach called as $this->loop inside the methods, but then have the foreach inside a method called public function loop().
All help would be appreciated.
So I have the two following methods inside my class:
public function check_missing_blobs(): void
{
$profiles = Profile::get([
'meta_query' => [
'relation' => 'OR',
[
'key' => 'azure_picture',
'value' => '',
'compare' => '='
],
[
'key' => 'azure_picture_big',
'value' => '',
'compare' => '='
],
]
]);
if (count($profiles) === 0) {
return;
}
foreach ($profiles as $profile) {
$profile->load([
'azure_picture' => Azure::init()->set_blob_sas_url
($profile->get_employee_id()),
'azure_picture_big' => Azure::init()->set_blob_sas_url
($profile->get_employee_id(), 'Big/'),
'azure_picture_expiration' =>
$profile->set_azure_picture_expiration
(strtotime('+7 days')),
'azure_picture_big_expiration' =>
$profile->set_azure_picture_big_expiration
(strtotime('+7 days')),
]);
$profile->save();
}
}
AND:
public function check_blob_expiration(string $days = '+2 days'): bool
{
$key = 'check_blob_expiration';
$settings = $this->get_settings($key);
if ($settings->started <= $settings->finished) {
$settings->started = time();
}
$profiles = Profile::get([
'post_status' => [
'publish', 'draft', 'pending', 'private'
],
'posts_per_page' => 250,
'meta_query' => [
'relation' => 'OR',
[
'key' => 'azure_picture_expiration',
'value' => strtotime($days),
'compare' => '<=',
],
[
'key' => 'azure_picture_big_expiration',
'value' => strtotime($days),
'compare' => '<=',
],
],
'paged' => $settings->page,
]);
if (count($profiles) === 0) {
$settings->page = 0;
$settings->finished = time();
echo '<pre>No azure blobs expiring within 2 days.</pre>';
return $this->set_settings($key, $settings);
}
foreach ($profiles as $profile) {
$profile->load([
'azure_picture' => Azure::init()->set_blob_sas_url
($profile->get_employee_id()),
'azure_picture_big' => Azure::init()->set_blob_sas_url
($profile->get_employee_id(), 'Big/'),
'azure_picture_expiration' =>
$profile->set_azure_picture_expiration
(strtotime('+7 days')),
'azure_picture_big_expiration' =>
$profile->set_azure_picture_big_expiration
(strtotime('+7 days')),
]);
$profile->save();
}
if (!empty($profiles)) {
$settings->page++;
} else {
$settings->page = 0;
$settings->finished = time();
}
return $this->set_settings($key, $settings);
}
You could envisage using a trait.
In short, a trait allows you to: reuse sets of methods freely in several independent classes living in different class hierarchies. (source: the manual).
An example to help better understand the concept:
Define a trait, call it e.g. Iterate, here it has one function loop(array $arr)
Inside the class where you want to use function loop, use: use Iterate
Now, as you can see, we can invoke the function: $this->loop() inside class Test
.
<?php
trait Iterate
{
public function loop(array $arr)
{
foreach ($arr as $key => $value) {
echo 'key : ' . $key;
echo '<br />';
echo 'value : ' . $value;
echo '<br />';
}
}
}
class Test
{
use Iterate;
public function __construct($arr)
{
$this->loop($arr);
}
}
$arr = [1, 2, 3];
$test = new Test($arr);
Output:
key : 0
value : 1
key : 1
value : 2
key : 2
value : 3
Related
I have a multidimensional array and i need make a searchCategory($categories, $id) function, which have to return a value of 'title' properties.
it try this code, it work but only for one layer of multidimensional array.
Multidimensional array:
$categories = array( array(
"id" => 1,
"title" => "Обувь",
'children' => array(
array(
'id' => 2,
'title' => 'Ботинки',
'children' => array(
array('id' => 3, 'title' => 'Кожа'),
array('id' => 4, 'title' => 'Текстиль'),
),
),
array('id' => 5, 'title' => 'Кроссовки',),
)), array(
"id" => 6,
"title" => "Спорт",
'children' => array(
array(
'id' => 7,
'title' => 'Мячи'
)
) ), );
Code which i try solve problem:
function searchCategory($categories, $id) {
foreach($categories as $category) {
if($category['id'] == $id) {
echo $category['title'] . '<br>';
}
}
};
I need my function to look up the id value in all arrays and return the title in the case of the array found
Here is recursive iterator case for you, please go through inline doc for explanation
function searchCategory($categories, $id)
{
$arrayiter = new RecursiveArrayIterator($categories);
$iteriter = new RecursiveIteratorIterator($arrayiter);
foreach ($iteriter as $key => $value) {
// checking if iterator comes to point where key is id and value matched
if ($key == 'id' && $value == $id) {
// returning matched value with current iterator instance
return $iteriter->getInnerIterator()['title'];
}
}
return '';
}
echo searchCategory($categories, 2).'<br/>';
echo searchCategory($categories, 7);
Working demo.
RecursiveArrayIterator - This iterator allows to unset and modify values and keys while iterating over Arrays and Objects in the same way as the ArrayIterator. Additionally it is possible to iterate over the current iterator entry.
RecursiveIteratorIterator - Can be used to iterate through recursive iterators.
RecursiveIteratorIterator::getInnerIterator: Get inner iterator
you need to make your function recursively
Demo : https://3v4l.org/CR7CD
function searchCategory($categories, $id) {
foreach($categories as $category) {
if($category['id'] == $id)
echo $category['title'] . '<br>';
if(isset($category['children']))
searchCategory($category['children'],$id);
}
}
I want to get a variable from a class in a function , the variable has arrays and i want to print all of theme in foreach loop
Here is my code :
class MP {
public function mp_setup_fields() {
$fields_socialmedia = array(
array(
'label' => 'شبکه های اجتماعی',
'id' => '',
'type' => 'hidden',
'section' => 'mp_custom_section',
),
);
}
}
I want get $fields_socialmedia in my home page
class MP {
public function mp_setup_fields() {
$fields_socialmedia = array(
array(
'label' => 'شبکه های اجتماعی',
'id' => '',
'type' => 'hidden',
'section' => 'mp_custom_section',
),
);
return $fields_socialmedia;
}
}
At first create object of your class then call method of object like below
$mp = new MP();
$array = $mp->mp_setup_fields();
foreach ($array as $value){
foreach ($value as $key => $v){
echo $key ."=". $v;
}
}
I have function in class, which returns array with 4 3-4 rows. I have to use each value from related row in table values. I can print builded function atrray, and can print on parent file, but can not get values for elements for each row. Here is my class file:
<?php
class Anyclass
{
public function $monthly($array)
{
.
.
.
}
public function myfunction($array)
{
foreach ($ShowMonths as $duration) {
$array['Credit']['downpayment'] = 0;
$array['Credit']['duration'] = $duration;
$monthly = $this->monthly($array);
$Table['Options'][] = array(
'downpayment' => $array['Credit']['downpayment'],
'duration' => $array['Credit']['duration'],
'monthly' => $monthly,
'total' => $monthly * $array['Credit']['duration'] + $array['Credit']['downpayment']
);
}
print_r($Table);
}
}
Here is my main file
include_once('mypathtofile/FileWithClass.php');
$Cll = new NewOne();
$array = array(
'Rule' => array(
'rule_id' => 1,
'rule_name' => 'Mobile phones',
'interest' => 0.01,
'comission' => 0.01,
'best_offer_downpayment' => 0.5,
'best_offer_duration' => 6
),
'Product' => array(
'product_id' => 1,
'category_id' => 1,
'manufacturer_id' => 1,
'product_price' => 500
),
'Credit' => array(
'downpayment' => 100,
'duration' => 6
)
);
$prtst = $Cll->myfunction($array);
How can I call each elemet for each row?
I'm not sure what you are trying to do, but if you need to get each value in a multidimensional array - you can use recursion:
function get_value($array){
foreach($array as $item){
if(is_array($item)){
get_value($item);
} else {
echo $item;
}
}
}
I used ArrayDataProvider to mix models and then merged them into one data-provider. I used the data-provider in grid-view and everything is works fine.
But I need to order the grid-view by one column I tried a lot of solutions but none of them are worked.
This my model code (order by item_order )
public function getAllSelectedItemsInTheUnit($unitId, $grid = false)
{
$finalList = array();
$storiesList = array();
$activityList = array();
$breakList = array();
$stories = UnitStories::find()->joinWith(['story'])->where("unit_id=$unitId")->all();
if (count($stories) > 0) {
foreach ($stories as $item) {
$storiesList[] = [
'key' => self::TYPE_STORY . $item->id,
'id' => $item->id,
'title' => $item->story->title,
'type' => self::TYPE_STORY,
'item_order' => $item->unit_order,
];
}
}
$activities = UnitActivities::find()->joinWith(['activity'])->where("unit_id=$unitId")->all();
if (count($activities) > 0) {
foreach ($activities as $item) {
$activityList[] = [
'key' => self::TYPE_ACTIVITY . $item->id,
'id' => $item->id,
'title' => $item->activity->title,
'type' => self::TYPE_ACTIVITY,
'item_order' => $item->activity_order,
];
}
}
$breaks = UnitBreaks::find()->where("unit_id=$unitId")->all();
if (count($breaks) > 0) {
foreach ($breaks as $item) {
$breakList[] = [
'key' => self::TYPE_BREAK . $item->id,
'id' => $item->id,
'title' => $item->title,
'type' => self::TYPE_BREAK,
'item_order' => $item->unit_order,
];
}
}
$finalList = array_merge($storiesList, $activityList, $breakList);
$dataProvider = new ArrayDataProvider([
'allModels' => $finalList, 'key' => 'key',
'sort' => [
'attributes' => ['item_order'],
],
]);
return $dataProvider;
}
Any solution will be very good even sort array by pure PHP I guess will fix the problem .
You can use usort()
usort($finalList, function ($a, $b) {
return $a['item_order'] < $b['item_order'];
});
Add your condition in callback >, <, <= etc
$array = array(
array(
'id' => 1,
'name' => 'John Doe',
'upline' => 0
),
array(
'id' => 2,
'name' => 'Jerry Maxwell',
'upline' => 1
),
array(
'id' => 3,
'name' => 'Roseann Solano',
'upline' => 1
),
array(
'id' => 4,
'name' => 'Joshua Doe',
'upline' => 1
),
array(
'id' => 5,
'name' => 'Ford Maxwell',
'upline' => 1
),
array(
'id' => 6,
'name' => 'Ryan Solano',
'upline' => 1
),
array(
'id' =>7,
'name' => 'John Mayer',
'upline' => 3
),
);
I want to make a function like:
function get_downline($userid,$users_array){
}
Then i want to return an array of all the user's upline key with the value as $userid. I hope anyone can help. Please please...
You could do it with a simple loop, but let's use this opportunity to demonstrate PHP 5.3 anonymous functions:
function get_downline($id, array $array) {
return array_filter($array, function ($i) use ($id) { return $i['upline'] == $id; });
}
BTW, I have no idea if this is what you want, since your question isn't very clear.
If you need do search thru yours array by $id:
foreach($array as $value)
{
$user_id = $value["id"];
$userName = $value["name"];
$some_key++;
$users_array[$user_id] = array("name" => $userName, "upline" => '1');
}
function get_downline($user_id, $users_array){
foreach($users_array as $key => $value)
{
if($key == $user_id)
{
echo $value["name"];
...do something else.....
}
}
}
or to search by 'upline':
function get_downline($search_upline, $users_array){
foreach($users_array as $key => $value)
{
$user_upline = $value["upline"];
if($user_upline == $search_upline)
{
echo $value["name"];
...do something else.....
}
}
}
Code :
function get_downline($userid,$users_array)
{
$result = array();
foreach ($users_array as $user)
{
if ($user['id']==$userid)
$result[] = $user['upline'];
}
return result;
}
?>
Example Usage :
get_downline(4,$array);