Get variable from a function in a class - php

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

Related

Define foreach inside a method to avoid repetition

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

check in_array for nested array

I have an array in this format, and I want to check if a var is in the array from any of the keys link
$nav = array(
'Account Settings' => array(
'icon' => 'fa-cog',
'Account Settings' => array(
'link' => '/voip/settings?seq='.$seq,
'icon' => 'fa-cog',
),
'Provisioning' => array(
'link' => '/voip/provisioning?seq='.$seq,
'icon' => 'fa-wrench',
),
'E999 Data' => array(
'link' => '/voip/e999?seq='.$seq,
'icon' => 'fa-life-ring',
),
'Delete Account' => array(
'link' => '/voip/delete?seq='.$seq,
'icon' => 'fa-trash',
),
),
'Mailboxes' => array(
'link' => '/voip/mailboxes?seq='.$seq,
'icon' => 'fa-envelope',
),
'Telephone Numbers' => array(
'link' => '/voip/numbers?seq='.$seq,
'icon' => 'fa-hashtag',
),
);
I tried if(in_array($_GET["nav"], $nav) but it doesn't pick up the nested values
Is there a way to do this?
There's no readymade function to do that. Let's say you have:
$key = 'link';
$value = '/voip/e999?seq=' . $seq;
// and $nav your multidimensionnal array
You can write your own recursive function:
function contains_key_value_multi($arr, $key, $value) {
foreach ($arr as $k => $v) {
if ( is_array($v) && contains_key_value_multi($v, $key, $value) ||
$k === $key && $v === $value )
return true;
}
return false;
}
var_dump(contains_key_value_multi($nav, $key, $value));
You can use the spl classes to be able to loop over leafs of your multidimensionnal array. This time you don't need a recursive function:
$ri = new RecursiveIteratorIterator(new RecursiveArrayIterator($nav));
function contains_key_value($arr, $key, $value) {
foreach ($arr as $k => $v) {
if ( $k === $key && $v === $value )
return true;
}
return false;
}
var_dump(contains_key_value($ri, $key, $value));
Since you say the value is in link key then you can use array_column to isolate the link items.
if(in_array($_GET["nav"], array_column($nav['Account Settings'], "link")) || in_array($_GET["nav"], array_column(array_slice($nav, 1), "link"))){
This will first look at all link items in account settings, then slice out account settings and look at the other two subarrays for link items.
Test it here:
https://3v4l.org/pP2Nk

PHP how to get value from multidimensional array?

I have an array in a class and want to obtain the 'Apple' key value ('iPhone').
I assume a for each loop needs to be used.
How would I go about doing this?
UPDATE: I also need to specify the customerType and productType key values.
class Products {
public function products_list() {
$customerType = 'national';
$productType = 'phones';
$phoneType = 'Apple';
$productsArr = array();
$productsArr[] = array(
'customerType' => 'national',
'productType' => array(
'phones' => array(
'Apple' => 'iPhone',
'Sony' => 'Xperia',
'Samsung' => 'Galaxy'
),
'cases' => array(
'leather' => 'black',
'plastic' => 'red',
),
),
'international' => array(
'phones' => array(
'BlackBerry' => 'One',
'Google' => 'Pixel',
'Samsung' => 'Note'
),
'cases' => array(
'leather' => 'blue',
'plastic' => 'green'
),
)
);
}
}
I have created a function that you can more or less give it any product and it will return the key and value from the array
<?php
class Products
{
public function products_list()
{
$customerType = 'national';
$productType = 'phones';
$phoneType = 'Apple';
$productsArr[] = array(
'customerType' => 'national', 'productType' => array(
'phones' => array(
'Apple' => 'iPhone',
'Sony' => 'Xperia',
'Samsung' => 'Galaxy'
),
'cases' => array(
'leather' => 'black',
'plastic' => 'red',
),
),
'international' => array(
'phones' => array(
'BlackBerry' => 'One',
'Google' => 'Pixel',
'Samsung' => 'Note'
),
'cases' => array(
'leather' => 'blue',
'plastic' => 'green'
),
)
);
echo $this->get_value($phoneType, $productsArr) .'<br>';
echo $this->get_value($customerType, $productsArr) .'<br>';
echo $this->get_value($productType, $productsArr) .'<br>';
}
function get_value($product, array $products)
{
$iterator = new RecursiveIteratorIterator(new RecursiveArrayIterator($products), RecursiveIteratorIterator::CHILD_FIRST);
foreach ($iterator as $key => $value) {
if (is_string($value) && ($key == $product)) {
return 'key ->' . $key .' value ->'.$value;
}
}
return "";
}
}
$phone_products = new Products();
$phone_products->products_list();
To use it within the class just call
$this->get_value($phoneType, $productsArr);
from without the class call
$phone_products = new Products();
echo ($phone_products->get_value($phoneType, $productsArr));
//output: key ->Apple value ->iPhone
NB: $phoneType, $productsArr will either be defined the methods they are being used in or passed from other methods or define global variables within the class.
If you want single entry:
echo $productsArr[0]['productType']['phones']['Apple']."<br />";
If there are multiple data, you can use foreach:
foreach ($productsArr as $prod){
echo $prod['productType']['phones']['Apple']."<br />";
}
just try
foreach($productsArr[0]['productType']['phones'] as $phones){
echo $phones[$phoneType]; }
foreach($productsArr as $key1 => $data1 ){
if(is_array($data1))
foreach($data1 as $key2 => $data2 ){
if(is_array($data2))
foreach($data2 as $key3 => $data3 ){
if(array_key_exists('Apple', $data3)) {
echo $data3['Apple'] ."\n";
}
}
}
}

Know the element level in multidimensional array

Well, I am here again dealing with arrays in php. I need your hand to guide me in the right direction. Suppose the following array:
-fruits
--green
---limon
---mango
--red
---apple
-cars
--ferrari
---enzo
----blue
----black
---318
--lamborg
---spider
---gallardo
----gallado-96
-----blue
-----red
-----gallado-98
The - (hyphen) symbol only illustrates the deep level.
Well, I need to build another array (or whatever), because it should be printed as an HTML select as below:
-fruits
--green
---limon
---mango
--red
---apple
-cars
--ferrari
---enzo
----blue
----black
---318
--lamborg
---spider
---gallardo
----gallado-96
-----blue
-----red
-----gallado-98
Looks that for each level element, it should add a space, or hyphen to determinate that it belongs to a particular parent.
EDIT
The have provide an answer provideng my final code. The html select element will display each level as string (repeating the "-" at the begging of the text instead multi-level elements.
Here's a simple recursive function to build a select dropdown given an array. Unfortunately I'm not able to test it, but let me know if it works. Usage would be as follows:
function generateDropdown($array, $level = 1)
{
if ($level == 1)
{
$menu = '<select>';
}
foreach ($array as $a)
{
if (is_array($a))
{
$menu .= generateDropdown($a, $level+1);
}
else
{
$menu .= '<option>'.str_pad('',$level,'-').$a.'</option>'."\n";
}
}
if ($level == 1)
{
$menu = '</select>';
}
return $menu;
}
OK, I got it with the help of #jmgardhn2.
The data
This is my array:
$temp = array(
array(
'name' => 'fruits',
'sons' => array(
array(
'name' => 'green',
'sons' => array(
array(
'name' => 'mango'
),
array(
'name' => 'banana',
)
)
)
)
),
array(
'name' => 'cars',
'sons' => array(
array(
'name' => 'italy',
'sons' => array(
array(
'name' => 'ferrari',
'sons' => array(
array(
'name' => 'red'
),
array(
'name' => 'black'
),
)
),
array(
'name' => 'fiat',
)
)
),
array(
'name' => 'germany',
'sons' => array(
array(
'name' => 'bmw',
)
)
),
)
)
);
Recursive function
Now, the following function will provide an array with items like [level] => [name]:
function createSelect($tree, $items, $level)
{
foreach ($tree as $key)
{
if (is_array($key))
{
$items = createSelect($key, $items, $level + 1);
}
else
{
$items[] = array('level' => $level, 'text' => $key);
}
}
return $items;
}
Calling the funcion
Now, call the function as below:
$items = createSelect($temp, array(), 0);
Output
If you iterate the final $items array it will look like:
1fruits
2green
3mango
3banana
1cars
2italy
3ferrari
4red
4black
3fiat
2germany
3bmw

Quick Recursive search of all indexes within an array

Ok, so say I have an array as follows:
$buttons = array(
'mlist' => array(
'title' => 'Members',
'href' => $scripturl . '?action=mlist',
'show' => $context['allow_memberlist'],
'sub_buttons' => array(
'mlist_view' => array(
'title' => 'View the Member List',
'href' => $scripturl . '?action=mlist',
'show' => true,
),
'mlist_search' => array(
'title' => 'Search for Members',
'href' => $scripturl . '?action=mlist;sa=search',
'show' => true,
'is_last' => true,
),
),
),
'home' => array(
'title' => 'Home',
'href' => $scripturl,
'show' => true,
'sub_buttons' => array(
),
'is_last' => $context['right_to_left'],
),
'help' => array(
'title' => 'Help',
'href' => $scripturl . '?action=help',
'show' => true,
'sub_buttons' => array(
),
),
);
I need to sort through this array and return all indexes of it in another array as an index, and the values of these arrays will be the title. So it should return an array as follows:
array(
'mlist' => 'Members',
'mlist_view' => 'View the Member List',
'mlist_search' => 'Search for Members',
'home' => 'Home',
'help' => 'Help',
);
How can this be achieved easily? Basically, need the key of each array if a title is specified and need to populate both within another array.
The following snippet loops over all of the arrays (recursively) to extract the key/title pairs.
$index = array();
$iterator = new RecursiveIteratorIterator(new ParentIterator(new RecursiveArrayIterator($buttons)), RecursiveIteratorIterator::SELF_FIRST);
foreach ($iterator as $key => $value) {
if (array_key_exists('title', $value)) {
$index[$key] = $value['title'];
}
}
var_dump($index);
How can this be achieved easily?
initialize an empty, new array
foreach the $buttons array with key and value
extract title from value
set the key in the new array with the title
done.
Edit: In case a recursive array iterator catches too much (identifying elements as children while they are not - just being some other array), and you don't want to write an extension of the recursive iterator class, stepping through all children can be solved with some "hand written" iterator like this:
$index = array();
$childKey = 'sub_buttons';
$iterator = $buttons;
while(list($key, $item) = each($iterator))
{
array_shift($iterator);
$index[$key] = $item['title'];
$children = isset($item[$childKey]) ? $item[$childKey] : false;
if ($children) $iterator = $children + $iterator;
}
This iterator is aware of the child key, so it will only iterate over childs if there are some concrete. You can control the order (children first, children last) by changing the order:
if ($children) $iterator = $children + $iterator;
- or -
if ($children) $iterator += $children;
I'm sure my answer is not most efficient, but using many foreach loops and if checks, it can be done. However, with my solution if you nested another array inside of say 'mlist_view' that you needed to get a title from, it would not work. My solution works for a max of 2 arrays inside of arrays within buttons. A better (and more general purpose solution) would probably involve recursion.
$result = array();
foreach($buttons as $field => $value) {
foreach($value as $nF => $nV) {
if($nF === 'title') {
$result[$field] = $nV;
}
if(is_array($nV)) {
foreach($nV as $name => $comp) {
if(is_array($comp)) {
foreach($comp as $nnF => $nnV) {
if($nnF === 'title') {
$result[$name] = $nnV;
}
}
}
}
}
}
}
foreach($result as $f => $v) {
echo $f.": ".$v."<br/>";
}
This works for your value of $buttons, fairly simple:
function get_all_keys($arr) {
if (!is_array($arr)) return array();
$return = array();
foreach (array_keys($arr) as $key) {
if (is_array($arr[$key])
&& array_key_exists('title', $arr[$key]))
$return[$key] = $arr[$key]['title'];
$return = array_merge($return, get_all_keys($arr[$key]));
}
return $return;
}
echo "<pre>";
print_r(get_all_keys($buttons));
echo "</pre>";
Which returns:
Array
(
[mlist] => Members
[mlist_view] => View the Member List
[mlist_search] => Search for Members
[home] => Home
[help] => Help
)

Categories