PHP 在 foreach 中创建键 => 值对

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5951745/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 23:00:15  来源:igfitidea点击:

PHP create key => value pairs within a foreach

phparraysforeachkey-value

提问by BobFlemming

I want to create a key-value pairs in an array within a foreach. Here is what I have so far:

我想在 foreach 的数组中创建一个键值对。这是我到目前为止所拥有的:

function createOfferUrlArray($Offer) {
    $offerArray = array();

    foreach ($Offer as $key => $value) { 
        $keyval = array($key => $value[4] );

        array_push($offerArray,$keyval);
    }

    return $offerArray;
}   

If I declare the array within the foreach, it will overwrites it on each iteration, but defining it outside the foreach doesn't work either and causes triplets:

如果我在 foreach 中声明数组,它将在每次迭代时覆盖它,但在 foreach 之外定义它也不起作用并导致三元组:

array[0] => key => value
array[1] => key => value 

How do I make it so I only get key-value pairs like this?

我如何做到这样我只能得到这样的键值对?

key => value
key => value

回答by Emil Vikstr?m

Something like this?

像这样的东西?

foreach ($Offer as $key => $value) { 
  $offerArray[$key] = $value[4];
}

回答by Eric Leschinski

Create key value pairs on the phpsh commandline like this:

在 phpsh 命令行上创建键值对,如下所示:

php> $keyvalues = array();
php> $keyvalues['foo'] = "bar";
php> $keyvalues['pyramid'] = "power";
php> print_r($keyvalues);
Array
(
    [foo] => bar
    [pyramid] => power
)

Get the count of key value pairs:

获取键值对的数量:

php> echo count($offerarray);
2

Get the keys as an array:

将键作为数组获取:

php> echo implode(array_keys($offerarray));
foopyramid

回答by Karl Laurentius Roos

Create key-value pairs within a foreach like this:

在 foreach 中创建键值对,如下所示:

function createOfferUrlArray($Offer) {
    $offerArray = array();

    foreach ($Offer as $key => $value) {
        $offerArray[$key] = $value[4];
    }

    return $offerArray;
}

回答by Matěj Koubík

In PHP >= 5.3 it can be done like this:

在 PHP >= 5.3 中,可以这样做:

$offerArray = array_map(function($value) {
    return $value[4];
}, $offer);

回答by binaryLV

function createOfferUrlArray($Offer) {
    $offerArray = array();
    foreach ($Offer as $key => $value) { 
        $offerArray[$key] = $value[4];
    }
    return $offerArray;
}

or

或者

function createOfferUrlArray($offer) {
    foreach ( $offer as &$value ) {
        $value = $value[4];
    }
    unset($value);
    return $offer;
}