Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I create an array with key value pairs?

Tags:

arrays

php

People also ask

How do you create a key-value pair array?

const arr = [ {"name": "Rahul", "score": 89}, {"name": "Vivek", "score": 88}, {"name": "Rakesh", "score": 75}, {"name": "Sourav", "score": 82}, {"name": "Gautam", "score": 91}, {"name": "Sunil", "score": 79}, ];

Can array have key-value pairs?

Arrays in javascript are typically used only with numeric, auto incremented keys, but javascript objects can hold named key value pairs, functions and even other objects as well. Simple Array eg. We see above that we can loop a numerical array using the jQuery.

How do you generate key-value pairs?

If we suppose that your keyvaluepair has as a key a string and as a value an int, then you could try this one: clsName. PropertyName = new KeyValuePair<string, int>("keyName", 2); You don't need to use the any Add method.

How do I create a key-value pair array in TypeScript?

Use an index signature to define a key-value pair in TypeScript, e.g. const employee: { [key: string]: string | number } = {} . An index signature is used when we don't know all the names of a type's keys ahead of time, but we know the shape of their values.


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

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.


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.


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.


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