如何只选择和打印嵌套数组的值?

时间:2016-07-21 12:26:41

标签: php multidimensional-array foreach

我尝试仅从basename$member1的网址的$member2创建数组,依此类推到$member(n)

基本数组i使用这样的原因,因为我将它用于另一个foreach循环。

所以这个计划看起来像这样:

$member1 = 'http://www.bla-bla.com/aFolder/anotherFolder';
$member2 = 'http://www.yada-yada.com/yetAnotherFolder/innerFolder';
$member3 = 'http://www.boo-boo.com/abcs/folder';

//this is the main array
$teams = array(
    array("url" => $member1, "selector" => "a"),
    array("url" => $member2, "selector" => "input"),
    array("url" => $member3, "selector" => "h1"),...,...);

我想构建一个foreach,最后会创建一个值为basename($member(n))的数组。

我希望我的结果看起来像这样:

Array
(
    [0] => anotherFolder
    [1] => innerFolder
    [2] => folder
)

到目前为止,我已尝试过不同的方法来提取特定值但无济于事,我无法找到如何提取特定值的方法。 我很感激你的帮助。

5 个答案:

答案 0 :(得分:1)

$basenames = [];
foreach ($teams as $team) {
    $basenames[] = basename($team['url']);
}

答案 1 :(得分:1)

lowest

答案 2 :(得分:1)

如果我理解你的话,试试这个:

$resArray = array();

foreach($teams as $team){
    $resArray[] = basename($team['url']);
}

答案 3 :(得分:1)

使用array_mapbasename函数的解决方案:

...
$result = array_map(function($v){ return basename($v['url']); }, $teams);

答案 4 :(得分:1)

$array = array();

foreach($teams as $team){
        $array[] = basename($team["url"]);
}
print_r($array);

将打印

Array
(
    [0] => anotherFolder
    [1] => innerFolder
    [2] => folder
)