Create an Assoc Array with Equal Keys and Values from a Regular Array

Create an assoc array with equal keys and values from a regular array

You can use the array_combine function, like so:

$numbers = array('first', 'second', 'third');
$result = array_combine($numbers, $numbers);

How to create an associative array with the same keys by having two normal arrays in Javascript

Hmm this introduces some consistancy concerns, since you don't have any kind of key to correlate values, but if you're 100% sure you will always have two arrays of the same length and each position of one relates to the some position of the other, then you can use this:

let arr_name = ["alice", "igor", "prince"]
let arr_slug = ["link_1", "link_2", "link_3"]

let result = arr_name.reduce((data, name, index) => {
data.push( {
'tag_info': {
name: name,
slug: arr_slug[index]
}
})
return data;

}, []);

Have in mind this won't result in the structure you showed, because it's impossible, as stated by @Nick Parsons, since it's an invalid JSON

How to set array key same as value

$array = array('first','second','third');

$newArray = array();
foreach($array as $value) {
$newArray[$value] = $value;
}

Or just initialize the array as you wanted to:

$array = array(
'first' => 'first',
'second' => 'second'
);

How to use keys/values from regular array to create associative array in Java 8?

It is possible to use Stream API to convert array into map in a functional way:

  • use IntStream.range to create a stream of integers
  • collected into map using Collectors.toMap:

For a new map, filter operation can be applied to select values less than 5.

// these imports to be added
import java.util.*;
import java.util.stream.*;

int [] array = {8, 3, 2, 9, 1, 15};
Map<Integer, Integer> map = IntStream.range(0, array.length) // stream of int indexes
.boxed() // stream of Integer
.collect(Collectors.toMap(
i -> i, // use index as key
i -> array[i] // get array element as value
));

Map<Integer, Integer> mapNew = IntStream.range(0, array.length)
.boxed()
.filter(i -> array[i] < 5)
.collect(Collectors.toMap(i -> i, i -> array[i] + 5));

System.out.println("old map:" + map);
// printing each entry in new map using lambda
mapNew.forEach((k, v) -> System.out.println(k + " -> " + v));

// use common for loop by entries
System.out.println("----");
for(Map.Entry<Integer, Integer> entry : mapNew.entrySet()) {
System.out.println(entry.getKey() + " => " + entry.getValue());
}

Output:

old map:{0=8, 1=3, 2=2, 3=9, 4=1, 5=15}
1 -> 8
2 -> 7
4 -> 6
----
1 => 8
2 => 7
4 => 6

Create an associative array using another array as keys

Since you've left out an explanation of what $values is I've guessed a little. Here are two scenarios.

If your values are all at the same level like below, we can chunk them up:

$keys = [ "SessionID", "Title", "Description", "Level", "Type", ];
$values = [
1,
"Title A",
"Desc A",
"Monster",
"car",
2,
"Title B",
"Desc B",
"Devil",
"car",
];

Cut the data up in to arrays with length equal to the number of keys.

$chunks = array_chunk($values, count($keys));

Then map them using array_combine like you suggested.

$ass = array_map(function ($chunk) use ($keys) {
return array_combine($keys, $chunk);
}, $chunks);

If your array is an array of arrays (or rows) we can skip the chunking part and pass it to the mapping function directly:

$values = [
[ 1, "Title A", "Desc A", "Monster", "car" ],
[ 2, "Title B", "Desc B", "Devil", "car" ]
];

$ass = array_map(function ($chunk) use ($keys) {
return array_combine($keys, $chunk);
}, $values);

Convert array of key-value pairs into associative array

If I understand you right, the final result can be obtained by doing:

array_combine(array_column($arr, 0), array_column($arr, 1));

Or, in a more traditional way:

$result = [];
foreach ($arr as list($key, $value)) {
$result[$key] = $value;
}

PHP Associative Array Duplicate Keys

No, you cannot have multiple of the same key in an associative array.

You could, however, have unique keys each of whose corresponding values are arrays, and those arrays have multiple elements for each key.

So instead of this...

42=>56 42=>86 42=>97 51=>64 51=>52

...you have this:

Array (
42 => Array ( 56, 86, 97 )
51 => Array ( 64, 52 )
)

Merge the associative array with multiple keys

You can do it like below:-

$final_array = array();

foreach($Array1 as $key=>$val){
if(is_array($val) && is_array($Array2[$key])){
if(array_keys($val)[0] == array_keys($Array2[$key])[0]){
$final_array[$key][array_keys($val)[0]] = $Array1[$key][array_keys($Array1[$key])[0]]+$Array2[$key][array_keys($Array2[$key])[0]];
}
}

}

print_r($final_array);

Output:- https://eval.in/834913

A slight better approach:-

$final_array = array();

if(count($Array1) >= count($Array2)){

foreach($Array1 as $key=>$val){
if(is_array($val) && is_array($Array2[$key])){
$final_array[$key][array_keys($val)[0]] = $Array1[$key][array_keys($Array1[$key])[0]]+$Array2[$key][array_keys($Array2[$key])[0]];
}else{
$final_array[$key] = $val;
}
}
}
if(count($Array1) < count($Array2)){

foreach($Array2 as $key=>$val){
if(is_array($val) && is_array($Array1[$key])){
$final_array[$key][array_keys($val)[0]] = $Array1[$key][array_keys($Array1[$key])[0]]+$Array2[$key][array_keys($Array2[$key])[0]];
}else{
$final_array[$key] = $val;
}
}
}

print_r($final_array);

Output:- https://eval.in/835143

Saving both variable name and content into associative array in php

You can use compact() to accomplish this.

Assuming the variables you are using are declared and have assigned values, you can use it like this:

$ar_var = compact('name', 'id', 'start_date', 'end_date', 'status', 'details');

Example: https://3v4l.org/8jnCe

php compare 2 associative arrays and combine on the same Key only

There are many ways to reach your goal. One of them is to use array_intersect_key() to keep the values of $array_2 only for keys it has in common with $array_1 and merge only this intersection into $array_1.

Something like:

$results = array_merge($array_1, array_intersect_key($array_2, $array_1));


Related Topics



Leave a reply



Submit