如何在PHP的foreach循环中附加值

时间:2019-05-28 05:45:38

标签: php php-7

print_r($studName);输出

Array
(
    [100] => Array
        (
            [firstName] => Krishna
        )

    [200] => Array
        (
            [firstName] => Goutham
        )
)

Array
(
    [300] => Array
        (
            [firstName] => A
        )

    [400] => Array
        (
            [firstName] => B
        )
)

print_r($studList);输出

Array
(
    [0] => 100
    [1] => 200
)

Array
(
    [0] => 300
    [1] => 400
)

现在我的问题是print_r($studList)100表示他在studName中的名字,我想找到它。我尝试过,但无法正常工作,

$mainArray = [];
foreach ($hobbies as $hobbieID => $hobbieName) {
// i am using loop inside another loop
        foreach ($studList as $value) {
            $mainArray[$value]['name'] = (isset($studName[$value]['firstName']) ? $studName[$value]['firstName'] : '');

        }
}

上面的代码我会像下面的输出

Array
(
    [100] => Array
        (
            [firstName] => Krishna
        )

    [200] => Array
        (
            [firstName] => Goutham
        )
    [100] => Array
        (
            [firstName] => Krishna
        )

    [200] => Array
        (
            [firstName] => Goutham
        )
    [300] => Array
        (
            [firstName] => A
        )

    [400] => Array
        (
            [firstName] => B
        )
)

1 个答案:

答案 0 :(得分:1)

我不太清楚您实际上想要什么,但是我认为您希望在不重复相同值的情况下获得所需的输出数组(显示的内容)。

执行以下操作:-

is.na(newdate) ~ paste0(substr(x=date, start = 10, stop = 13), "-", 
                            substr(x=date, start = 14, stop = 15), "-",
                            substr(x=date, start = 16, stop = 17) )

输出:-{https://3v4l.org/sD8up

如果两个数组的结构都始终相同(意味着$finalArray = array(); foreach( $studList as $studLi){ foreach($studLi as $studL){ foreach( $studName as $studNam){ foreach( $studNam as $key=>$studNa){ if($studL == $key){ $finalArray[$studL]['firstName'] = $studNa['firstName']; } } } } } 的第一个数字将始终是$studList的第一个索引) ,则如下所示:-

$studName

输出:-https://3v4l.org/1mH5C