PHP create key => value pairs within a foreach

2019-03-12 09:43发布

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

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:

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

5条回答
做自己的国王
2楼-- · 2019-03-12 10:05

Create key-value pairs within a foreach like this:

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

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

    return $offerArray;
}
查看更多
走好不送
3楼-- · 2019-03-12 10:08

Something like this?

foreach ($Offer as $key => $value) { 
  $offerArray[$key] = $value[4];
}
查看更多
兄弟一词,经得起流年.
4楼-- · 2019-03-12 10:11

Create key value pairs on the phpsh commandline like this:

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
查看更多
三岁会撩人
5楼-- · 2019-03-12 10:14

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

$offerArray = array_map(function($value) {
    return $value[4];
}, $offer);
查看更多
6楼-- · 2019-03-12 10:31
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;
}
查看更多
登录 后发表回答