将值嵌套在foreach循环中

时间:2014-04-30 12:42:39

标签: php

我有一系列循环,我需要让值正确传递。基本上我有来自joomla的hikashop的产品对象。为了让我的显示器以我希望它的方式工作,我不得不将图像分成单独的数组并使用array_unique来过滤重复的图像,因为hikashop为每个产品变体分配默认值并且正在重复显示屏上每个变体的图像。我需要显示屏来显示每个已过滤的图像,但是然后将$char_id分配给它们图像,以便在单击它时它将更改主要产品图像。

我的目标是,图像显示正确,但它只为每张图像拾取$characteristic->variant_characteristic_id中的第一个键,而不是为每张图像获取唯一键。

我担心我在这里有点过头了,谢谢

这是我的代码块:

if ($this->element->variants):
    $i = 0;
    foreach($this->element->variants as $variant):
        foreach($variant->characteristics as $k => $characteristic):
            $char_id = $characteristic->variant_characteristic_id;
            $cat_id = $k;
            $char_name = $characteristic->characteristic_value;
            foreach($variant->images as $key => $image):
                $images[$i] = array($key => $image);
                $i++;
            endforeach;
            $images = array_map("unserialize", array_unique(array_map("serialize", $images)));
        endforeach;
    endforeach;
    echo '<pre>'.print_r($images).'</pre>';
    foreach($images as $image):
        echo '
            <div class="product-thmb-group">
                <img id="hikashop_child_image_'.$char_id.'" class="hikashop_child_image" src="' . $this->image->uploadFolder_url . $image[0]->file_path . '" alt="hikashop_child_image_' . $char_id . '"  />
                <span class="product-thmb-title">'.$char_name.'</span>
            </div>';
    endforeach;
endif;

1 个答案:

答案 0 :(得分:0)

如果你还提供了一个示例有效载荷,有效载荷就是其中的任何内容,这将有所帮助 $这 - &GT;元素 - &GT;变体

无论如何发现问题很简单,你要覆盖的价值观 在循环的每次迭代中$char_id, $cat_id, $char_name

您还要为$variant->characteristics中的每个项目迭代所有图像一次,这可能不是您想要的。 如果没有看到您尝试解析的有效负载,我只能猜测,但我想 你想要做的是:

$i = 0;
$images = [];
foreach($this->element->variants as $variant) {
    $characteristic = $variant->characteristics[$i];
    $image = $variant->images[$i];

    $images[$image] = [
        "id" => $characteristic->variant_characteristic_id,
        "name" => $characteristic->characteristic_value,
        "image" => $image, // this is optional
    ];
    $i++;
}

然后你应该能够遍历数组

foreach($images as $image => $meta) {
    echo "Image src: ", $image,
         " Id: ", $meta['id'], " Name: ", $meta['name'], "\n";
}

或者如果您保留上面的可选作业

foreach($images as $data) {
    echo "Image src: ", $data['image'],
         " Id: ", $data['id'], " Name: ", $data['name'], "\n";
}
相关问题