【问题标题】:How to target multiple instances of an array in php? [closed]如何在php中定位数组的多个实例? [关闭]
【发布时间】:2013-06-28 10:33:28
【问题描述】:

我在定义我要查找的内容时遇到了一些麻烦,所以希望我不会听起来很神秘。

我正在尝试从我的网上商店的数组中获取一些内容,该数组存储订单中每个商品的订单信息。

我想返回此订单信息中的一些值。但是我在定位正确的信息时遇到了一些麻烦。由于我想为每个单独的 order_item 返回此信息,因此我需要定位唯一键,并可能为每个函数编写一个。我不知道从哪里开始。

我当前返回的数组看起来像这样。例如,我将如何返回两个 product_id?

array(2) {
["d4650547c8d3536a6741b300f563a8fb"]=>
array(11) {
["product_id"]=>
int(259)
["variation_id"]=>
int(278)
["variation"]=>
array(1) {
["pa_afmetingen-liggend"]=>
string(4) "m011"
}
["quantity"]=>
int(1)
["data"]=>
object(WC_Product_Variation)#3243 (24) {  ["variation_id"]=>
int(278)
["parent"]=>
}
["product_type"]=>
string(8) "variable"
}

array(2) {
["893hg547c8d35pga6741b300f56754ud"]=>
array(11) {
["product_id"]=>
int(279)
["variation_id"]=>
int(298)
["variation"]=>
array(1) {
["pa_afmetingen-liggend"]=>
string(4) "m011"
}
["quantity"]=>
int(1)
["data"]=>
object(WC_Product_Variation)#3243 (24) {  ["variation_id"]=>
int(298)
["parent"]=>
}
["product_type"]=>
string(8) "variable"
}

【问题讨论】:

    标签: php arrays return


    【解决方案1】:

    你在寻找这样的东西吗?

    代码

    <?php
        // Sample products Array
        $my_products = array();
        $my_products[] = array('product_id' => 230, 'product_name' => 'audi');
        $my_products[] = array('product_id' => 355, 'product_name' => 'benz');
    
        // My products
        print_r($my_products);
    
        $product_ids = array();
        foreach ($my_products as $product) {
          $product_ids[] = $product['product_id'];
        }
    
        // MY product ids
        print_r($product_ids);
    
        // My first product id
        echo $my_products[0]['product_id'];
    
        // My second product id
        echo $my_products[1]['product_id'];
    ?>
    

    输出

    // My products
    
          Array
        (
            [0] => Array
                (
                    [product_id] => 230
                    [product_name] => audi
                )
    
            [1] => Array
                (
                    [product_id] => 355
                    [product_name] => benz
                )
    
        )
    
    // MY product ids
    
    Array
    (
        [0] => 230
        [1] => 355
    )
    
    // My first product id
    230
    
    // My second product id
    355
    

    【讨论】:

    • 这对我帮助很大!有没有办法自动输出?在您的示例中,您针对每个回显使用相应的数字,有没有办法动态回显每个条目的 product_id?
    • 是的。见第二个输出。 (for循环)
    • 我的意思是重写 // 我的第一个产品 id echo $my_products[0]['product_id']; // 我的第二个产品 id echo $my_products[1]['product_id'];对所有可能的 id 的单个语句。所以即使有 15 个 ID。
    • 回声 $product['product_id'];在 for each 中成功了。再次感谢您的代码。加分和选择。
    猜你喜欢
    • 2016-08-16
    • 1970-01-01
    • 2015-05-18
    • 1970-01-01
    • 1970-01-01
    • 2021-10-07
    • 1970-01-01
    • 2019-01-06
    • 1970-01-01
    相关资源
    最近更新 更多