Переберите оператор foreach и добавьте в пустой многомерный массив

Я пытаюсь заполнить пустой массив именем и значением из цикла foreach. Я создал массив $variationimages = array(); и в цикле я сохраняю значения с помощью $variationimages['name'] а также $variationimages['image'],

При возврате $variationimages массив я получаю только первый элемент

Array
(
[name] = Wall Profile
[image] = <img src="example-image.jpg">
)

Я хотел бы, чтобы он возвращал что-то подобное ниже и имел бы возможность доступа к определенному элементу в массиве, используя что-то вроде $variationimages['Roof Profile']['image'] который вернул бы изображение предмета с названием «Профиль крыши».

 Array
(
[name] = Wall Profile
[image] = <img src="example-image.jpg">
),
(
[name] = Roof Profile
[image] = <img src="example-image.jpg">
),

У меня есть код ниже:

function loop_display_variation_attribute_and_thumbnail() {
global $product;

// HERE your targeted product attribute taxonomy
$taxonomy = 'pa_product_type';
$variationimages = array();

if( $product->is_type('variable') ) {
foreach ( $product->get_available_variations() as $variation ) {

if( isset($variation['attributes']['attribute_'.$taxonomy]) ) {
// Get the "pa_product_type"$term_name = get_term_by('slug', $variation['attributes']['attribute_'.$taxonomy], $taxonomy)->name;
$term_slug = get_term_by('slug', $variation['attributes']['attribute_'.$taxonomy], $taxonomy)->slug;

$variationimages['name'] = get_term_by('slug', $variation['attributes']['attribute_'.$taxonomy], $taxonomy)->name;
$variationimages['image'] = '<img style="display:none;" class="'.$term_slug.'-image" src="' . $variation['image']['thumb_src'] .'">';
}
}
echo "<div style='display:none'>";
print_r($variationimages);
echo "</div>";
}
}

0

Решение

Шон, просто добавь дополнительный [] к своей переменной здесь:

$variationimages['name'][] = get_term_by('slug', $variation['attributes']['attribute_'.$taxonomy], $taxonomy)->name;
$variationimages['image'][] = '<img style="display:none;" class="'.$term_slug.'-image" src="' . $variation['image']['thumb_src'] .'">';

На каждой итерации он будет добавлять новые значения.

Ура 😉

—РЕДАКТИРОВАТЬ после комментария —

$variationimages[] = [
'name'  => get_term_by('slug', $variation['attributes']['attribute_'.$taxonomy], $taxonomy)->name,
'image' => '<img style="display:none;" class="'.$term_slug.'-image" src="' . $variation['image']['thumb_src'] .'">'
];
1

Другие решения

я думаю, что вы должны заполнить массив объектами или массивом массивов

например, вы должны создать класс, например, Item $one_item= new Item();

и напишите такой код:

function loop_display_variation_attribute_and_thumbnail() {
global $product;

// HERE your targeted product attribute taxonomy
$taxonomy = 'pa_product_type';
$variationimages = array();

if( $product->is_type('variable') ) {
foreach ( $product->get_available_variations() as $variation ) {

if( isset($variation['attributes']['attribute_'.$taxonomy]) ) {
// Get the "pa_product_type"$term_name = get_term_by('slug', $variation['attributes']['attribute_'.$taxonomy], $taxonomy)->name;
$term_slug = get_term_by('slug', $variation['attributes']['attribute_'.$taxonomy], $taxonomy)->slug;
$one_item=New Item ();

$one_item=>name = get_term_by('slug', $variation['attributes']['attribute_'.$taxonomy], $taxonomy)->name;
$one_item=>image = '<img style="display:none;" class="'.$term_slug.'-image" src="' . $variation['image']['thumb_src'] .'">';
array_push($variationimages,$one_item);

}
}
echo "<div style='display:none'>";
print_r($variationimages);
echo "</div>";
}
}
0

По вопросам рекламы ammmcru@yandex.ru
Adblock
detector