【问题标题】:How to match 2 arrays, and loop through to display an array value?如何匹配 2 个数组,并循环显示数组值?
【发布时间】:2017-03-24 05:25:10
【问题描述】:

我正在尝试匹配两个数组,如果匹配,则循环遍历数组值以将它们显示在页面上。

这就是我的做法。

$productIDs = array(
    '0' => array(
        'product_id' => '565355',
        'product_name' => 'stackPDF',
        'product_file' => 'http://www.example.com/stack.pdf',
    ),
    '1' => array(
        'product_id' => '563423',
        'product_name' => 'lostPDF',
        'product_file' => 'http://www.example.com/lost.pdf',
    ),
    '3' => array(
        'product_id' => '4442',
        'product_name' => 'No product',
        'product_file' => '',
    )
);

function getProducts($productIDs){

    $getIDs  = explode(',', $_GET['product_id']);

    $intersection = array();
    foreach($productIDs as $items)
    {
        $intersection[] = array_intersect($items, $getIDs);
    }

    if(!empty($intersection)){
        return $intersection;
    } else {
        echo "There are no products available!";
    }
}
$getProducts = getProducts($productIDs);

function getDownloads($getProducts){

    foreach($getProducts as $item){
        print_r($item);
    }

}
$getDownloads = getDownloads($getProducts);

在 getProducts() 函数中,我正在检查标头中的 product_id 是否与 $productIDs 中的任何 product_id 匹配,以便仅显示标头中的可用链接。

$getProducts 变量具有可用的product_id,它已经在数组中匹配,并且在 $getDownloads 中我试图“如果 id 可用,则循环并显示来自多维数组的 product_file 参数值”但是我似乎无法遍历它,而是无法弄清楚如何匹配它/返回值。

【问题讨论】:

    标签: php arrays


    【解决方案1】:
    array_filter($array, function($v) use($id){ return $v['product_id'] == $id;})
    

    【讨论】:

      【解决方案2】:

      我能想到的最简单的方法是:

      $item_exists =  array_filter($productIDs, function($item) use ($check) {
          return md5(json_encode($item)) == md5(json_encode($check));
      });
      

      json_encode 将数组序列化为字符串,md5 将创建一个比较键,如果它们相等,它将插入到$item_exists 数组中。

      编辑:我正在考虑比较产品对象,但我想你只需要 ID,你可以使用这样的东西:

      $existing_values = array_filter($productIDs, function($p)use($getIDs){
           return in_array($p["product_id"], $getIDs); 
      });
      

      【讨论】:

      • 它一直返回“Array”,就是这样。
      • 您需要print_rvar_dump 现有值数组。
      • 我使用了 print_r,我尝试的第一件事就是“数组”。 var_dump 只返回 "array(0) { } "
      • print_r 不会返回数组。也许这是其他东西的输出?
      猜你喜欢
      • 1970-01-01
      • 2017-05-21
      • 2017-07-29
      • 1970-01-01
      • 1970-01-01
      • 2017-03-25
      • 2017-02-12
      • 1970-01-01
      • 2021-05-24
      相关资源
      最近更新 更多