Php在不同的数组键中搜索相同的值

时间:2017-12-29 05:44:33

标签: php arrays multidimensional-array foreach

这是我的小脚本,但目前没有得到正确的结果:

<?php

    // Delimiters betweeb data "*" elements in each data delimiters ","
    $data_string="house1,403,phone1*house2,404,phone2*house3,403,phone3*house4,405,phone3";
    // Explode $data_string for "~" delimiter
    $data_exp=explode("*",$data_string);
    //

    // Loop 1
    foreach($data_exp as $data_1)
    {
        $data_exp_compar=explode(",",$data_1);

        // We want see the elements with the same data in common in second position (403,404,etc)
        $data_common_1[]=$data_exp_compar[1];
        $data_common_2[]=$data_exp_compar[1];
    }

    $a=array_values(array_intersect_key($data_common_1,$data_common_2));
    $b=array_count_values(array_intersect_key($data_common_1,$data_common_2));

    foreach($a as $aa=>$values)
    {
        echo $aa;
        print "<br>";
    }

?>

这个脚本中的想法。它会扫描“$ data_string”中的数据,如您所见,所有数据分隔符都是“*”,并且在每个数据中我们都有“,”作为分隔符的元素

我想以这种格式获得此输出结果:

PRODUCT Id: 403 (2 Actually)

1-  house1,403,phone1
2-  house3,403,phone3 

PRODUCT Id: 404 (1 Actually)

1 - house2,404,phone2

Product Id: 405 (1 Actually)

1 - house4,405,phone4

正如您所看到的,唯一的比较因素是它在第二个位置,它是产品的ID

我尝试了许多东西,但我无法获得作品,或者最终得到结果,因为我想要表演

感谢所有人先进,尊重

2 个答案:

答案 0 :(得分:1)

您可以先将它们分组,然后再打印另一个foreach循环以打印结果

$data_string="house1,403,phone1*house2,404,phone2*house3,403,phone3*house4,405,phone3";
$data_exp = explode("*",$data_string);

$group = []; // Initialize group array
foreach($data_exp as $data_1)
{
    $data_exp_compar=explode(",",$data_1);
    $group[$data_exp_compar[1]][] = $data_exp_compar; // Group by the number key after exploding
}

// Loop to each group, then print desired format
foreach ($group as $key => $value) {
    echo 'Product ID: ' . $key . ' (' . count($value) . ' Actually)<br>';
    foreach ($value as $k => $v) {
        echo ++$k . ' - ' . implode(',', $v) . '<br>';
    }
    echo '<br>';
}

答案 1 :(得分:0)

我建议使用array_map和array_filter函数。如果您对此有任何疑问,请与我们联系。

<?php

// Prepare data and input
$id = 403;
$data = "house1,403,phone1*house2,404,phone2*house3,403,phone3*house4,405,phone3";

// Convert string data to array
$data = explode("*", $data);
$data = array_map(function ($row) {
    return explode(",", $row);
}, $data);

// Search the array
$response = array_filter($data, function ($row) use ($id) {
    return $row[1] == $id;
});

print_r($response);