在explode()创建的多维数组上插入重复值

时间:2018-01-13 23:02:06

标签: php arrays curl domdocument

这是我的脚本及其背后的逻辑

////There's some more stuff right here but it's not really relevant. Right now 
////Because I'm doing tests i'm doing I'm limiting it to 3 posts in `$my_query`

//create empty arrays before loop to initialize array
$array = array();

//start loop (each contains a my way of getting a new url)
while ($my_query->have_posts()) : $my_query->the_post();

//misc stuff to get the URL, SKU and ID
$post_id = get_the_ID();
$product = wc_get_product(get_the_ID());
$title = $product->get_title();
$sku = $product->get_sku();
$sku_id = $sku . '_' . $post_id;
$urltitle = urlencode($title);

//assign url
$url = 'http://www.example.com/search?=' . $urltitle;

//Using CURL to get HTML from $url
$ch = curl_init();
$timeout = 5;
curl_setopt($ch, CURLOPT_URL, surl);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
$html = curl_exec($ch);
curl_close($ch);

$dom = new DOMDocument();

@$dom->loadHTML($html);

//retreive links from loaded html
foreach($dom->getElementsByTagName('a') as $link) {

//search nodeValue's for something specific in string
if (strpos($link->nodeValue, 'Over $') !== false) {

    //nodeValue found. Start counter and make $f not empty
    $f = 1;
                                                  }
        //$f is now not empty
        if (!empty($f)) {

                //Starting at nodeValue's immediately after 'Over $'
                if ($f > 1) {

                        //Put nodeValue's in $array along with corresponding $sku and $id
                        $array[] .= $link->nodeValue . '|' . $sku_id;

                            }
//increment $f by +1 once $f is not empty
$f++;
}

//we only want the first 4 values after the searched text was found ($f = 2, 3, 4 and 5)
if ($f == 6) {
                        break;
}

//end foreach loop         
}

//make $f empty again so it remains false at beginning of while loop (don't completely understand this but I was having issues without it)
$f = NULL;

//end loop. Start again.
endwhile;

在循环之后,数组存储我获得的值并输出正常。

Array
(
    [0] => Motor Vehicle Wheel Parts|SKU1_9545
    [1] => Motor Vehicle Suspension Parts|SKU1_9545
    [2] => CarParts.com|SKU1_9545
    [3] => Auto Parts Train|SKU1_9545
    [4] => Automotive Rims & Wheels|SKU2_8564
    [5] => Motor Vehicle Suspension Parts|SKU2_8564
    [6] => Under 16 inch|SKU2_8564
    [7] => 16 – 18 inch|SKU2_8564
    [8] => Motor Vehicle Wheel Parts|SKU3_7589
    [9] => Motor Vehicle Suspension Parts|SKU3_7589
    [10] => McGard|SKU3_7589
    [11] => Rugged Ridge|SKU3_7589
)

因为我双方都有重复的键和值,所以我需要将它变为多维数组,并将$ sku_id作为父数组。

这就是我的集合:

foreach ($array as $key => $level):
        $explode = explode('|', $level);
       foreach ($itemprods as $k =>$attribute):
           $explode = explode('|', $attribute);
             $variables[$explode[1]][] = $explode[0];
       endforeach;
endforeach;

由于$variables的输出为

,因此这似乎稍有效果
Array
(
    [SKU1_9545] => Array
        (
            [0] => Motor Vehicle Wheel Parts
            [1] => Motor Vehicle Suspension Parts
            [2] => CarParts.com
            [3] => Auto Parts Train
            [4] => Motor Vehicle Wheel Parts
            [5] => Motor Vehicle Suspension Parts
            [6] => CarParts.com
            [7] => Auto Parts Train
            [8] => Motor Vehicle Wheel Parts
            [9] => Motor Vehicle Suspension Parts
            [10] => CarParts.com
            [11] => Auto Parts Train
            [12] => Motor Vehicle Wheel Parts
            [13] => Motor Vehicle Suspension Parts
            [14] => CarParts.com
            [15] => Auto Parts Train
            [16] => Motor Vehicle Wheel Parts
            [17] => Motor Vehicle Suspension Parts
            [18] => CarParts.com
            [19] => Auto Parts Train
            [20] => Motor Vehicle Wheel Parts
            [21] => Motor Vehicle Suspension Parts
            [22] => CarParts.com
            [23] => Auto Parts Train
            [24] => Motor Vehicle Wheel Parts
            [25] => Motor Vehicle Suspension Parts
            [26] => CarParts.com
            [27] => Auto Parts Train
            [28] => Motor Vehicle Wheel Parts
            [29] => Motor Vehicle Suspension Parts
            [30] => CarParts.com
            [31] => Auto Parts Train
            [32] => Motor Vehicle Wheel Parts
            [33] => Motor Vehicle Suspension Parts
            [34] => CarParts.com
            [35] => Auto Parts Train
            [36] => Motor Vehicle Wheel Parts
            [37] => Motor Vehicle Suspension Parts
            [38] => CarParts.com
            [39] => Auto Parts Train
            [40] => Motor Vehicle Wheel Parts
            [41] => Motor Vehicle Suspension Parts
            [42] => CarParts.com
            [43] => Auto Parts Train
            [44] => Motor Vehicle Wheel Parts
            [45] => Motor Vehicle Suspension Parts
            [46] => CarParts.com
            [47] => Auto Parts Train
        )

    [SKU2_8564] => Array
        (
            [0] => Automotive Rims & Wheels
            [1] => Motor Vehicle Suspension Parts
            [2] => Under 16 inch
            [3] => 16 – 18 inch
            [4] => Automotive Rims & Wheels
            [5] => Motor Vehicle Suspension Parts
            [6] => Under 16 inch
            [7] => 16 – 18 inch
            [8] => Automotive Rims & Wheels
            [9] => Motor Vehicle Suspension Parts
            [10] => Under 16 inch
            [11] => 16 – 18 inch
            [12] => Automotive Rims & Wheels
            [13] => Motor Vehicle Suspension Parts
            [14] => Under 16 inch
            [15] => 16 – 18 inch
            [16] => Automotive Rims & Wheels
            [17] => Motor Vehicle Suspension Parts
            [18] => Under 16 inch
            [19] => 16 – 18 inch
            [20] => Automotive Rims & Wheels
            [21] => Motor Vehicle Suspension Parts
            [22] => Under 16 inch
            [23] => 16 – 18 inch
            [24] => Automotive Rims & Wheels
            [25] => Motor Vehicle Suspension Parts
            [26] => Under 16 inch
            [27] => 16 – 18 inch
            [28] => Automotive Rims & Wheels
            [29] => Motor Vehicle Suspension Parts
            [30] => Under 16 inch
            [31] => 16 – 18 inch
            [32] => Automotive Rims & Wheels
            [33] => Motor Vehicle Suspension Parts
            [34] => Under 16 inch
            [35] => 16 – 18 inch
            [36] => Automotive Rims & Wheels
            [37] => Motor Vehicle Suspension Parts
            [38] => Under 16 inch
            [39] => 16 – 18 inch
            [40] => Automotive Rims & Wheels
            [41] => Motor Vehicle Suspension Parts
            [42] => Under 16 inch
            [43] => 16 – 18 inch
            [44] => Automotive Rims & Wheels
            [45] => Motor Vehicle Suspension Parts
            [46] => Under 16 inch
            [47] => 16 – 18 inch
        )

    [SKU3_7589] => Array
        (
            [0] => Motor Vehicle Wheel Parts
            [1] => Motor Vehicle Suspension Parts
            [2] => McGard
            [3] => Rugged Ridge
            [4] => Motor Vehicle Wheel Parts
            [5] => Motor Vehicle Suspension Parts
            [6] => McGard
            [7] => Rugged Ridge
            [8] => Motor Vehicle Wheel Parts
            [9] => Motor Vehicle Suspension Parts
            [10] => McGard
            [11] => Rugged Ridge
            [12] => Motor Vehicle Wheel Parts
            [13] => Motor Vehicle Suspension Parts
            [14] => McGard
            [15] => Rugged Ridge
            [16] => Motor Vehicle Wheel Parts
            [17] => Motor Vehicle Suspension Parts
            [18] => McGard
            [19] => Rugged Ridge
            [20] => Motor Vehicle Wheel Parts
            [21] => Motor Vehicle Suspension Parts
            [22] => McGard
            [23] => Rugged Ridge
            [24] => Motor Vehicle Wheel Parts
            [25] => Motor Vehicle Suspension Parts
            [26] => McGard
            [27] => Rugged Ridge
            [28] => Motor Vehicle Wheel Parts
            [29] => Motor Vehicle Suspension Parts
            [30] => McGard
            [31] => Rugged Ridge
            [32] => Motor Vehicle Wheel Parts
            [33] => Motor Vehicle Suspension Parts
            [34] => McGard
            [35] => Rugged Ridge
            [36] => Motor Vehicle Wheel Parts
            [37] => Motor Vehicle Suspension Parts
            [38] => McGard
            [39] => Rugged Ridge
            [40] => Motor Vehicle Wheel Parts
            [41] => Motor Vehicle Suspension Parts
            [42] => McGard
            [43] => Rugged Ridge
            [44] => Motor Vehicle Wheel Parts
            [45] => Motor Vehicle Suspension Parts
            [46] => McGard
            [47] => Rugged Ridge
        )

)

有更有效的方法吗? 多维数组中的所有值都是正确的,我只需要找出一种方法来删除每个维度中的重复值。

我期待实现的最终结果将如下所示

Array
(
    [SKU1_9545] => Array
        (
            [0] => Motor Vehicle Wheel Parts
            [1] => Motor Vehicle Suspension Parts
            [2] => CarParts.com
            [3] => Auto Parts Train
        )

    [SKU2_8564] => Array
        (
            [0] => Automotive Rims & Wheels
            [1] => Motor Vehicle Suspension Parts
            [2] => Under 16 inch
            [3] => 16 – 18 inch
        )

    [SKU3_7589] => Array
        (
            [0] => Motor Vehicle Wheel Parts
            [1] => Motor Vehicle Suspension Parts
            [2] => McGard
            [3] => Rugged Ridge
        )

)

3 个答案:

答案 0 :(得分:2)

在第二部分中不需要两个循环。这对我有用:

$variables=[];
foreach ($myArray as $row){
     $explode = explode('|', $row);
     if (!in_array($explode[1],array_keys($variables))){
         $variables[$explode[1]]=[];
     }
     $variables[$explode[1]][] = $explode[0];
}

答案 1 :(得分:1)

所以这一点:

foreach ($itemprods as $k =>$attribute):
    $explode = explode('|', $attribute);
    $variables[$explode[1]][] = $explode[0];

添加支票

foreach ($itemprods as $k =>$attribute):
    $explode = explode('|', $attribute);
    if( !isset($variables[$explode[1]]) || array_search($explode[0], $variables[$explode[1]]) === false)
         $variables[$explode[1]][] = $explode[0];

http://php.net/manual/en/function.array-search.php

  

array_search - 在数组中搜索给定值,并在成功时返回第一个相应的键

请注意=== false这意味着(额外=)也要检查类型。这是必要的,因为array_search返回的索引可以是00也是false,但它不是" boolean" false。因此,如果搜索说它是数组中的第一个元素,即索引0,这会阻止添加项目。

在文档中给出了这个警告:

  

警告此函数可能返回布尔值FALSE,但也可能返回非布尔值,其值为FALSE。有关更多信息,请阅读有关布尔值的部分。使用===运算符测试此函数的返回值。

或者你可以运行array_unique,但这需要在编译多维数组后进行循环。

  foreach( $variables as &$array){
     $array = array_unique($array);
  }

&中的as &$array是通过引用传递的,因此我们可以在不创建新数组的情况下更新数组。

最后一种方式是滥用密钥是唯一的这一事实,并使用与其值相匹配的密钥创建嵌套数组:

foreach ($itemprods as $k =>$attribute):
    $explode = explode('|', $attribute);
    if(!isset($variables[$explode[1]]) || !isset($variables[$explode[1]][$explode[0]]))
         $variables[$explode[1]][$explode[0]] = $explode[0];

最后一个是最快的,因为isset没有进行函数调用。但你最终会得到一个像这样的数组:

[SKU1_9545] => Array
    (
        [Motor Vehicle Wheel Parts] => Motor Vehicle Wheel Parts
        [Motor Vehicle Suspension Parts] => Motor Vehicle Suspension Parts
        [CarParts.com] => CarParts.com
        [Auto Parts Train] => Auto Parts Train
    )

您可以使用array_values删除密钥,例如array_values($array['SKU1_9545']),但这有点会破坏目的。

<强>更新

正如你在评论中提到的那样,对于我提到的第一种和最后一种方式,你应该检查是否首先设置主阵列。

 if( !isset($variables[$explode[1]]) || ... )

当PHP看到OR的第一部分为真时,它不会评估第二部分,因为整个条件都是真的。因此,先检查另一个是非常重要的。所以我们可以检查OR因为如果没有设置主嵌套数组,那么它中的元素肯定不会重复。

答案 2 :(得分:1)

假设这是输入数组:

$array = Array(
                "0" => "Motor Vehicle Wheel Parts|SKU1_9545",
                "1" => "Motor Vehicle Suspension Parts|SKU1_9545",
                "2" => "CarParts.com|SKU1_9545",
                "3" => "Auto Parts Train|SKU1_9545",
                "4" => "Automotive Rims & Wheels|SKU2_8564",
                "5" => "Motor Vehicle Suspension Parts|SKU2_8564",
                "6" => "Under 16 inch|SKU2_8564",
                "7" => "16 – 18 inch|SKU2_8564",
                "8" => "Motor Vehicle Wheel Parts|WS49X4_9874",
                "9" => "Motor Vehicle Suspension Parts|WS49X4_9874",
                "10" => "McGard|WS49X4_9874",
                "11" => "Rugged Ridge|WS49X4_9874"
               );

然后,您可以使用result arrayarray_key_exists(),如下所示:

$results = array();     // array to keep results

foreach($array as $key => $value)
{
    $explode = explode('|', $value);             // exlpode the value

    if(!array_key_exists($explode[1], $results)) // check if key already exists in results
    {
        $results[$explode[1]] = array();       // if not make a new key
    }

    array_push($results[$explode[1]], $explode[0]);  // push a value to the key
}

print_r($results);

将输出:

Array ( 
        [SKU1_9545] => Array ( [0] => Motor Vehicle Wheel Parts 
                               [1] => Motor Vehicle Suspension Parts 
                               [2] => CarParts.com 
                               [3] => Auto Parts Train
                             )
        [SKU2_8564] => Array ( [0] => Automotive Rims & Wheels
                               [1] => Motor Vehicle Suspension Parts
                               [2] => Under 16 inch [3] => 16 – 18 inch
                             )
        [WS49X4_9874] => Array([0] => Motor Vehicle Wheel Parts
                               [1] => Motor Vehicle Suspension Parts
                               [2] => McGard
                               [3] => Rugged Ridge
                              )
      )