tags:

views:

3014

answers:

3

how can I add key value pairs to an array?

This won't work:

public function getCategorieenAsArray(){

     $catList = array();

       $query = "SELECT DISTINCT datasource_id, title FROM table";
       if ($rs=C_DB::fetchRecordset($query)) {
          while ($row=C_DB::fetchRow($rs)) { 
           if(!empty($row["title"])){
            array_push($catList, $row["datasource_id"] ."=>". $row["title"] );

           }
           }
        }         

     return($catList);
    }

Because it gives me:

Array ( [0] => 1=>Categorie 1 [1] => 5=>Categorie 2 [2] => 2=>Caterorie 2 )

and I expect

Array ( [1] =>Categorie 1 [5] => Categorie 2 )

+2  A: 

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.

WCWedin
+2  A: 

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.

Gumbo
A: 

$data =array(); $data['user_code'] = 'JOY' ; $data['user_name'] = 'JOY' ; $data['user_email'] = '[email protected]';

joy