PHP create key => value pairs within a foreach

后端 未结 5 976
傲寒
傲寒 2021-02-04 04:58

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();

         


        
相关标签:
5条回答
  • 2021-02-04 05:16

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

    $offerArray = array_map(function($value) {
        return $value[4];
    }, $offer);
    
    0 讨论(0)
  • 2021-02-04 05:18

    Something like this?

    foreach ($Offer as $key => $value) { 
      $offerArray[$key] = $value[4];
    }
    
    0 讨论(0)
  • 2021-02-04 05:18

    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
    
    0 讨论(0)
  • 2021-02-04 05:26
    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;
    }
    
    0 讨论(0)
  • 2021-02-04 05:27

    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;
    }
    
    0 讨论(0)
提交回复
热议问题