How can I create an array with key value pairs?

PhpArrays

Php Problem Overview


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  ) 

Php Solutions


Solution 1 - Php

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

Solution 2 - Php

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.

Solution 3 - Php

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.

Solution 4 - Php

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.

Solution 5 - Php

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;
}

Solution 6 - Php

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'];            
   }

}
          

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionsandersView Question on Stackoverflow
Solution 1 - PhpjoyView Answer on Stackoverflow
Solution 2 - PhpGumboView Answer on Stackoverflow
Solution 3 - PhpIsabelle WedinView Answer on Stackoverflow
Solution 4 - PhpRajan RawalView Answer on Stackoverflow
Solution 5 - PhpMahmoudView Answer on Stackoverflow
Solution 6 - PhpranojanView Answer on Stackoverflow