Answer the question
In order to leave comments, you need to log in
How to access array elements?
Friends, maybe someone knows
why we sometimes access array keys through square brackets: $locations[ $menu_name ]
and sometimes like this: $menu_item->url (inside the loop)
I get confused all the time.
Here is an example code from wp-kama.ru. I understand what it does, but these calls to properties are confused all the time.
// Получим элементы меню на основе параметра $menu_name (тоже что и 'theme_location' или 'menu' в аргументах wp_nav_menu)
// Этот код - основа функции wp_nav_menu, где получается ID меню из слага
$menu_name = 'custom_menu_slug';
$locations = get_nav_menu_locations();
if( $locations && isset($locations[ $menu_name ]) ){
$menu = wp_get_nav_menu_object( $locations[ $menu_name ] ); // получаем меню
$menu_items = wp_get_nav_menu_items( $menu ); // получаем элементы меню
// создаем список
$menu_list = '<ul id="menu-' . $menu_name . '">';
foreach ( (array) $menu_items as $key => $menu_item ){
$menu_list .= '<li><a href="' . $menu_item->url . '">' . $menu_item->title . '</a></li>';
}
$menu_list .= '</ul>';
}
else
$menu_list = '<ul><li>Меню "' . $menu_name . '" не определено.</li></ul>';
Answer the question
In order to leave comments, you need to log in
$locations[ $menu_name ]
- array $menu_item->url
- object
The concept element refers to an array, property - to an object .
I will add that in addition to full-fledged classes, there is also StdClass - an empty default class out of the box, to which properties can be assigned.
$o = new \StdClass;
$o->prop1 = '123123';
$o->prop2 = 'xxxxxx';
$o = (array)$o;
echo $o['prop1'];
$arr = ['test1' => 1, 'test2' => 2];
$o = (object)$arr;
echo $o->test1;
You don't know OOP if you ask this question
How to access the elements of an array?
$numbers = array(1,2,3);
echo $numbers[0]; // prints 1
How to access objects?
class Numbers {
public $one = 1;
public $two = 2;
public $three = 3;
}
$object = new Numbers();
echo $object->one; // prints 1
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question