【问题标题】:PHP Foreach returns separated(individual) arraysPHP Foreach 返回分离的(单独的)数组
【发布时间】:2018-07-08 02:45:06
【问题描述】:

在 foreach 循环中创建的数组是单独的,如下面的结果。我需要它们位于父数组中。

Array
(
    [0] => Array
        (
            [url] => https://example.com/product/osaka-entry-tee-superdry-6/
            [img] => <img width="114" height="130" src="//storage.googleapis.com/example-stateless/2017/11/489b0847-538228-0286_1-114x130.jpeg" class="attachment-shop_thumbnail size-shop_thumbnail wp-post-image wp-stateless-item" alt="" data-image-size="shop_thumbnail" data-stateless-media-bucket="example-stateless" data-stateless-media-name="2017/11/489b0847-538228-0286_1.jpeg" />
            [name] => OSAKA ENTRY TEE SUPERDRY 6
            [desc] => Superdry mens Big Dry Entry t-shirt. A crew neck t-shirt featuring a large Dry cracked print with embossed JPN logos within the print, a Super print on one sleeve and the t-shirt is finished with a Superdry logo tab on one sleeve. Specifications: - Material: cotton 100% Care: - Wash: machine wash - cold (30°C) - Bleach: do not bleach - Dry: line dry - Iron: iron - low - Dry clean: do not dry clean
            [seller_url] => https://example.com/trade/project-store/
            [author_name] => Project Store
            [slug] => <a href="https://example.com/product/osaka-entry-tee-superdry-6/" class="button product_type_simple add_to_cart_button" target="_self" ><span>GO TO SHOP</span></a>
            [geoinfo] => Array
                (
                    [0] => -22.9813
                    [1] => -47.0265
                )

        )

)
Array
(
    [0] => Array
        (
            [url] => https://example.com/product/on1-jersey-unif/
            [img] => <img width="114" height="130" src="//storage.googleapis.com/example-stateless/2018/01/b1b0193f-258836-0426_1-510x600-114x130.jpeg" class="attachment-shop_thumbnail size-shop_thumbnail wp-post-image wp-stateless-item" alt="" data-image-size="shop_thumbnail" data-stateless-media-bucket="example-stateless" data-stateless-media-name="2018/01/b1b0193f-258836-0426_1-510x600.jpeg" />
            [name] => ON1 JERSEY UNIF
            [desc] => UNIF offers a collection of contemporary womenswear that features iconic graphic T-shirts as well fashion-forward silhouettes. Expect edgy details, bold prints, and pieces fit for the modern downtown girl. 100% poly. Unlined. Embroidered logo detailing on front, back and sleeves. Revolve Style No. UNIX-WD35. Manufacturer Style No. USJ-4006.
            [seller_url] => https://example.com/trade/project-store/
            [author_name] => Project Store
            [slug] => <a href="https://example.com/product/on1-jersey-unif/" class="button product_type_simple add_to_cart_button" target="_self" ><span>GO TO SHOP</span></a>
            [geoinfo] => Array
                (
                    [0] => -23.0313
                    [1] => -46.9725
                )

        )

)

Bellow 是创建上述结果的函数。 $tradesInfo 数组是在嵌套的 foreach 循环之外声明的,但它并没有解决问题!此函数是与 Woocommerce 和 Dokan 一起使用的 Wordpress 脚本的一部分。

if($pageposts)
{
    $tradesInfo = Array();

    foreach($pageposts as $prd)
    {
        if (!is_object($prd)) {
            $query = $wpdb->get_results("SELECT * FROM wp_geo_location WHERE productid=" . $prd . "");
        } else {
            $query = $wpdb->get_results("SELECT * FROM wp_geo_location WHERE productid=" . $prd->post_id . "");
        }

        $array = json_decode(json_encode($query), true);

        foreach($array as $plots)
        {
            $product = wc_get_product($plots["productid"]);

            $author = get_user_by('id', $product->post->post_author);

            // Add cart button or reservation link
            $slug = basename(get_permalink());

            if (function_exists('dokan_get_store_url')) {
                $sellerurl = dokan_get_store_url($author->ID);
            } else {
                $sellerurl = '';
            }

            // Get parent cat ID by product ID
            $prod_terms = get_the_terms($plots["productid"], 'product_cat');

            foreach ($prod_terms as $prod_term) {
                // gets product cat id
                $product_cat_id = $prod_term->term_id;

                // gets an array of all parent category levels
                    $product_parent_categories_all_hierachy = get_ancestors($product_cat_id, 'product_cat');

                // This cuts the array and extracts the last set in the array
                $last_parent_cat = array_slice($product_parent_categories_all_hierachy, -1, 1, true);

                foreach ($last_parent_cat as $last_parent_cat_value) {
                    // $last_parent_cat_value is the id of the most top level category, can be use whichever one like
                    $catID = $last_parent_cat_value;
                }
            }

            $tmp = '<a href="' . get_permalink($product->get_id()) . '" class="button product_type_simple add_to_cart_button" target="_self" ><span>' . __("GO TO SHOP", "pinnergeolocation") . '</span></a>';

            // PRODUCT INFO IN GOOGLE MAP
            if($product != "")
            {
                if ($slug == "medicaments") {
                    $result_slug = printf('<br><a href="%s" title=" ' .__("More Details", "pinnergeolocation") . ' "><span color="#fa6a6a"><b>%s</b></span></a>', esc_url(get_permalink($product->get_id())), __("More Info", "pinnergeolocation"));
                } else {
                    $result_slug = str_replace(array("\n", "\r"), '', $tmp);
                }

                $tradesInfo[] = array(
                    "url" => esc_url(get_permalink($plots["productid"])),
                    "img" => $product->get_image(),
                    "name" => mb_strtoupper(get_the_title($plots["productid"]), "UTF-8"),
                    "desc" => preg_replace('/\s+/', ' ', get_the_excerpt( $product->post )),
                    "seller_url" => $sellerurl,
                    "author_name" => $author->display_name,
                    "slug" => $result_slug,
                    "geoinfo" => array($plots["latitude"], $plots["longitude"])
                );

                $tradesJSON = json_encode($tradesInfo);

                echo $tradesJSON;
            }
        }
    }
}

【问题讨论】:

  • 好的,继续?什么不工作?你试过什么?请向我们提供有关您想要什么以及您尝试过什么的更多信息。
  • 发布你用来创建这个结构的代码..
  • 我们无法修复我们看不到的代码
  • 对不起!我已经添加了产生我之前发布的结果的函数。

标签: php arrays json foreach


【解决方案1】:

假设这是你的代码:

foreach($var as $arr){
    $myarray=....; // here you get your array
    print_r($myarray);
}

改变它,将每个数组插入另一个数组:

$wrapArray=array();
foreach($var as $arr){
    $myarray=....; // here you get your array
    $wrapArray[]=$myarray;

}
print_r($wrapArray);

【讨论】:

  • 先让op编辑问题,不用开始猜了。
  • 感谢托比亚!你确实是对的!我把你的答案标记为正确的!
猜你喜欢
  • 2016-05-09
  • 1970-01-01
  • 1970-01-01
  • 2021-11-26
  • 2019-01-26
  • 1970-01-01
  • 1970-01-01
  • 2017-08-23
  • 1970-01-01
相关资源
最近更新 更多