How can I create an array with key value pairs?

后端 未结 6 544
名媛妹妹
名媛妹妹 2020-12-23 16:00

How can I add key value pairs to an array?

This won\'t work:

public function getCategorieenAsArray(){

    $catList = array();

    $query = \"SELECT         


        
相关标签:
6条回答
  • 2020-12-23 16:03

    Use the square bracket syntax:

    if (!empty($row["title"])) {
        $catList[$row["datasource_id"]] = $row["title"];
    }
    

    $row["datasource_id"] is the key for where the value of $row["title"] is stored in.

    0 讨论(0)
  • 2020-12-23 16:06

    No need array_push function.if you want to add multiple item it works fine. simply try this and it worked for me

    class line_details {
       var $commission_one=array();
       foreach($_SESSION['commission'] as $key=>$data){
              $row=  explode('-', $key);
              $this->commission_one[$row['0']]= $row['1'];            
       }
    
    }
    
    0 讨论(0)
  • 2020-12-23 16:16

    My PHP is a little rusty, but I believe you're looking for indexed assignment. Simply use:

    $catList[$row["datasource_id"]] = $row["title"];
    

    In PHP arrays are actually maps, where the keys can be either integers or strings. Check out PHP: Arrays - Manual for more information.

    0 讨论(0)
  • 2020-12-23 16:18

    You can create the single value array key-value as

    $new_row = array($row["datasource_id"]=>$row["title"]);
    

    inside while loop, and then use array_merge function in loop to combine the each new $new_row array.

    0 讨论(0)
  • 2020-12-23 16:21

    You can use this function in your application to add keys to indexed array.

    public static function convertIndexedArrayToAssociative($indexedArr, $keys)
    {
        $resArr = array();
        foreach ($indexedArr as $item)
        {
            $tmpArr = array();
            foreach ($item as $key=>$value)
            {
                $tmpArr[$keys[$key]] = $value;
            }
            $resArr[] = $tmpArr;
        }
        return $resArr;
    }
    
    0 讨论(0)
  • 2020-12-23 16:26
    $data =array();
    $data['user_code']  = 'JOY' ;
    $data['user_name']  = 'JOY' ;
    $data['user_email'] = 'joy@cargomar.org';
    
    0 讨论(0)
提交回复
热议问题