在 PHP 中将多维数组转换为单数组

php中如何将多维数组转换为单个数组?我花了几个小时来寻找解决方案,但找不到适合我的解决方案。这是我的代码:


<?php


$arrContextOptions=array(

    "ssl"=>array(

        "verify_peer"=>false,

        "verify_peer_name"=>false,

        "http" => array(

            "header" => "User-Agent: Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.102 Safari/537.36"

        )

    )

);


$source_url = 'http://netsparker.com/';

$html = file_get_contents($source_url,false, stream_context_create($arrContextOptions));

$dom = new DOMDocument;

@$dom->loadHTML($html);

$links = $dom->getElementsByTagName('a');



foreach ($links as $link) {

    $result_url = $link->getAttribute('href');



    if (!preg_match('/^https?:\/\//', $result_url)) {

        $result_url = $source_url . preg_replace('/^\//', '', $result_url);



    }

    $array2 = array($result_url);

    print_r($array2);

}




?>


Array

(

    [0] => http://github.com/#start-of-content

)

Array

(

    [0] => https://help.github.com/articles/supported-browsers

)

Array

(

    [0] => https://github.com/

)

Array

(

    [0] => http://github.com/join?ref_cta=Sign+up&ref_loc=header+logged+out&ref_page=%2F&source=header-home

)

Array

(

    [0] => http://github.com/features

)

Array

(

    [0] => http://github.com/features/code-review/

)

Array

(

    [0] => http://github.com/features/project-management/

)


....


我想把它变成:


Array

(

    [0] => http://github.com/

    [1] => http://github.com/collections

    [2] => http://github.com/topics

    [3] => http://github.com/explore

    [4] => http://github.com/enterprise

    .......

我尝试使用 foreach、ArrayIterator、flatten 但似乎不起作用。我还尝试将 result_url 转换为数组,但也不起作用。



杨魅力
浏览 114回答 1
1回答

肥皂起泡泡

尝试将值推送到foreach循环中的单个数组中:$array2 = [];foreach ($links as $link) {&nbsp; &nbsp; $result_url = $link->getAttribute('href');&nbsp; &nbsp; if (!preg_match('/^https?:\/\//', $result_url)) {&nbsp; &nbsp; &nbsp; &nbsp; $result_url = $source_url . preg_replace('/^\//', '', $result_url);&nbsp; &nbsp; }&nbsp; &nbsp; $array2[] = $result_url;}print_r($array2);
打开App,查看更多内容
随时随地看视频慕课网APP