I have string
$string1 = `a,b,c,d`;
$array1 = explode(',', $string1);
Gives me :
array(
(int) 0 => 'a',
(int) 1 => 'b',
(int) 2 => 'c'
(int) 3 => 'd'
)
But I want it to be like this
array(
'a' => 'a',
'b' => 'b',
'c' => 'c'
'd' => 'd'
)
How do I do that
Use array_combine function
$string = `a,b,c,d`;
$array = explode(',', $string);
var_dump(array_combine($array, $array));
I think you have to create a new array after exploding...
$tmp_arr = explode(',', $string1);
$array1 = array();
foreach ($tmp_arr as $item){
$array1[$item] = $item;
}
Related
I have two arrays:
$a = ['0' => 1, '1' => 2, '2' => 3]
$b = ['0' => 4, '1' => 5, '2' => 6]
I want to create a new array like this:
[
['a' => 1, 'b' => '4'],
['a' => '2', 'b' => '5']
]
I have tried using array_merge and array_merge_recursive, but I wasn't able to get the right results.
$data = array_merge_recursive(array_values($urls), array_values($id));
You have to apply array_map() with custom function:
$newArray = array_map('combine',array_map(null, $a, $b));
function combine($n){
return array_combine(array('a','b'),$n);
}
print_r($newArray);
Output:-https://3v4l.org/okML7
Try this one
$c = array_merge($a,$b)
$d[] = array_reduce($d, 'array_merge', []);
It will merge the two array and reduce and remerge it.
You can use foreach to approach this
$a = ['0' => 1, '1' => 2, '2' => 3];
$b = ['0' => 4, '1' => 5, '2' => 6];
$res = [];
$i = 0;
$total = 2;
foreach($a as $k => $v){
$res[$i]['a'] = $v;
$res[$i]['b'] = $b[$k];
$i++;
if($i == $total) break;
}
The idea is to have an array $ab = ['a','b'] and a array from your both arrays like this $merged_array = [[1,4],[2,5],[3,6]]. Now we can combine array $ab with each element of $merged_array and that will be the result we need.
$first = ['0' => 1, '1' => 2, '2' => 3];
$second = ['0' => 4, '1' => 5, '2' => 6];
$merged_array = [];
for($i=0;$i<count($first);$i++)
{
array_push($merged_array,[$first[$i],$second[$i]]);
}
$final = [];
$ab = ['a','b'];
foreach($merged_array as $arr)
{
array_push($final,array_combine($ab, $arr));
}
print_r($final);
All earlier answers are working too hard. I see excessive iterations, iterated function calls, and counter variables.
Because there are only two arrays and the keys between the two arrays are identical, a simple foreach loop will suffice. Just push associative arrays into the result array.
Code: (Demo)
$a = ['0' => 1, '1' => 2, '2' => 3];
$b = ['0' => 4, '1' => 5, '2' => 6];
$result = [];
foreach ($a as $k => $v) {
$result[] = ['a' => $v, 'b' => $b[$k]];
}
var_export($result);
Output:
array (
0 =>
array (
'a' => 1,
'b' => 4,
),
1 =>
array (
'a' => 2,
'b' => 5,
),
2 =>
array (
'a' => 3,
'b' => 6,
),
)
I would like to take an array like this and combine it into 1 single array.
array (size=2)
0 =>
array (size=10)
0 => string '1'
1 => string 'a'
2 => string '3'
3 => string 'c'
1 =>
array (size=5)
0 => string '2'
1 => string 'b'
However I want the array results to be interleaved.
So it would end up looking like
array
0 => '1'
1 => '2'
2 => 'a'
3 => 'b'
4 => '3'
5 => 'c'
I would like it so that it doesn't matter how many initial keys are passed in (this one has 2), it should work with 1, 2 or 5. Also, as you can see from my example the amount of elements most likely won't match.
Anyone know the best way to accomplish this?
$data = array(
0 => array(
0 => '1',
1 => 'a',
2 => '3',
3 => 'c',
),
1 => array(
0 => '2',
1 => 'b',
),
);
$newArray = array();
$mi = new MultipleIterator(MultipleIterator::MIT_NEED_ANY);
$mi->attachIterator(new ArrayIterator($data[0]));
$mi->attachIterator(new ArrayIterator($data[1]));
foreach($mi as $details) {
$newArray = array_merge(
$newArray,
array_filter($details)
);
}
var_dump($newArray);
I had fun with this... So if you like it use it!
$arr1 = [1,'a',3,'c'];
$arr2 = ['2','b'];
$finarry = arrayInterweave($arr1,$arr2);
print_r($finarry);
function arrayInterweave($arr1,$arr2){
$count1 = count($arr1);
$count2 = count($arr2);
$length = (($count1 >= $count2) ? $count1 : $count2);
$fin = array();
for($i = 0;$i<$length;$i++){
if(!empty($arr1[$i])){
$fin[] = $arr1[$i];
}
if(!empty($arr2[$i])){
$fin[] = $arr2[$i];
}
}
return $fin;
}
Tried to think of a fun solution:
$array = [
["a","b","c"],
["d","e"]
];
$result = [];
while($array) {
array_walk(
$array,
function(&$subarray, $key) use (&$array, &$result) {
$result[] = array_shift($subarray);
if(empty($subarray)) unset ($array[$key]);
}
);
}
var_dump($result);
It destroys the original array though.
After determining which row contains the most elements, you can loop through known indexes and push columns of data into the result array.
The following technique is safe to use with a variable number of rows.
Code: (Demo)
$maxCount = max(array_map('count', $array));
$result = [];
for ($i = 0; $i < $maxCount; ++$i) {
array_push($result, ...array_column($array, $i));
}
var_export($result);
Input/Output:
$array
$result
[['b', 'e', 'd', 's'], ['l', 'n']]
['b', 'l', 'e', 'n', 'd', 's']
['f', 'g', 'n', 's'], ['r', 'm'], ['a', 'e', 't']
['f', 'r', 'a', 'g', 'm', 'e', 'n', 't' 's']
The above technique is perfectly capable of accommodating 3 or more input arrays as well.
p.s. For anyone running into technical limitations because their php version, this will do the same:
$maxCount = max(array_map('count', $array));
$result = [];
for ($i = 0; $i < $maxCount; ++$i) {
foreach (array_column($array, $i) as $found) {
$result[] = $found;
}
}
...if your php version doesn't accommodate the above snippet, you really, really need to upgrade your php version (sorry, not sorry).
To avoid the counting to determine the longest subarray, you can instead transpose the data with nested loops then flatten that result structure. (Demo)
$result = [];
foreach ($array as $i => $row) {
foreach ($row as $k => $v) {
$result[$k][$i] = $v;
}
}
var_export(array_merge(...$result));
This question already has answers here:
How to sum all column values in multi-dimensional array?
(20 answers)
Closed 9 years ago.
i need to merge two associative arrays which may or may not contain same key,if key is same the values need to added and stored in the resultant array
$array1 = array(
'a' => 5,
'b' => 10,
'c' => 6,
'k' = > 10
);
$array2 = array(
'a' => 100,
'c' => 200,
'd' => 30,
'k' => 10
);
how to add the above two associative arrays and receive the following output/associative array -
$array2 = array(
'a' => 105,
'b' => 10,
'c' => 206,
'd' => 30,
'k' => 20
);
Try
$array1 = array(
'a' => 5,
'b' => 10,
'c' => 6,
'k' => 10
);
$array2 = array(
'a' => 100,
'c' => 200,
'd' => 30,
'k' => 10
);
$sums = array();
foreach (array_keys($array1 + $array2) as $key) {
$sums[$key] = (isset($array1[$key]) ? $array1[$key] : 0) + (isset($array2[$key]) ? $array2[$key] : 0);
}
print_r($sums);
$a3 = array_merge_recursive ($array1, $array2);
foreach ($a3 as $key => $value)
{
$a3[$key] = (is_array($value))?array_sum($value):$value;
}
for finding unique index value
$array2 =array_merge($array1,$array2);
and for finding unique value you can try
$array2 =array_unique(array_merge($array1,$array2));
I don't know if you can do this with an internal function but it is doable by simply iterating through both arrays.
function merge_add($array1, $array2)
{
$result = array();
merge_add_array($array1, $result);
merge_add_array($array2, $result);
return $result;
}
function merge_add_array($array, &$result)
{
foreach ($array as $key=>$value)
{
if (array_key_exists($key, $result))
{
$result[$key] += $value;
}
else
{
$result[$key] = $value;
}
}
}
$result = merge_add($array1, $array2);
The & will cause passing by reference
<?php
$array1 = array(
'a' => 5,
'b' => 10,
'c' => 6,
'k' => 10
);
$array2 = array(
'a' => 100,
'c' => 200,
'd' => 30,
'k' => 10
);
$keys = array_keys($array1 + $array2);
foreach ($keys as $key) {
$array2[$key] = isset($array1[$key]) && isset($array2[$key]) ? ($array1[$key] + $array2[$key]) : (isset($array1[$key]) ? $array1[$key] : $array2[$key]);
}
print_r($array2);
Here is an array I have:
$a = array('a' => 'a1', 'b' => 'a2', 'c' => 'a3', 'd' => 'a4', 'e' => 'a5');
What I would like to do is reverse the values of the array while keeping the keys intact, in other words it should look like this:
$a = array('a' => 'a5', 'b' => 'a4', 'c' => 'a3', 'd' => 'a2', 'e' => 'a1');
How should I go about it?
P.S. I tried using array_reverse() but it didn't seem to work
Some step-by-step processing using native PHP functions (this can be compressed with less variables):
$a = array('a' => 'a1', 'b' => 'a2', 'c' => 'a3', 'd' => 'a4', 'e' => 'a5');
$k = array_keys($a);
$v = array_values($a);
$rv = array_reverse($v);
$b = array_combine($k, $rv);
var_dump($b);
Result:
array(5) {
'a' =>
string(2) "a5"
'b' =>
string(2) "a4"
'c' =>
string(2) "a3"
'd' =>
string(2) "a2"
'e' =>
string(2) "a1"
}
It is possible by using array_combine, array_values, array_keys and array_values. May seem like an awful lot of functions for a simple task, and there may be easier ways though.
array_combine( array_keys( $a ), array_reverse( array_values( $a ) ) );
Here another way;
$keys = array_keys($a);
$vals = array_reverse(array_values($a));
foreach ($vals as $k => $v) $a[$keys[$k]] = $v;
I think this should work..
<?php
$old = array('a' => 'a1', 'b' => 'a2', 'c' => 'a3', 'd' => 'a4', 'e' => 'a5');
$rev = array_reverse($old);
foreach ($old as $key => $value) {
$new[$key] = current($rev);
next($rev);
}
print_r($new);
?>
This'll do it (just wrote it, demo here):
<?php
function value_reverse($array)
{
$keys = array_keys($array);
$reversed_values = array_reverse(array_values($array), true);
return array_combine($keys, $reversed_values);
}
$a = array('a' => 'a1', 'b' => 'a2', 'c' => 'a3', 'd' => 'a4', 'e' => 'a5');
print_r( value_reverse($a) );
I have two arrays, both have the same keys (different values) however array #2 is in a different order. I want to be able to resort the second array so it is in the same order as the first array.
Is there a function that can quickly do this?
I can't think of any off the top of my head, but if the keys are the same across both arrays then why not just loop over the first one and use its key order to create a new array using the the values from the 2nd one?
$arr1 = array(
'a' => '42',
'b' => '551',
'c' => '512',
'd' => 'gge',
) ;
$arr2 = array(
'd' => 'ordered',
'b' => 'is',
'c' => 'now',
'a' => 'this',
) ;
$arr2ordered = array() ;
foreach (array_keys($arr1) as $key) {
$arr2ordered[$key] = $arr2[$key] ;
}
You can use array_replace
$arr1 = [
'x' => '42',
'y' => '551',
'a' => '512',
'b' => 'gge',
];
$arr2 = [
'a' => 'ordered',
'x' => 'this',
'y' => 'is',
'b' => 'now',
];
$arr2 = array_replace($arr1, $arr2);
$arr2 is now
[
'x' => this,
'y' => is,
'a' => ordered,
'b' => now,
]
foreach(array_keys($array1) as $key)
{
$tempArray[$key] = $array2[$key];
}
$array2 = $tempArray;
I am not completely sure if this is what your after. anyways as long as the the array remains the same size, than this should work for you.
$gamey = array ("wow" => "World of Warcraft", "gw2" => "Guild Wars2", "wiz101" => "Wizard 101");
$gamex = array ("gw2" => "best game", "wiz101" => "WTF?", "wow" => "World greatest");
function match_arrayKeys ($x, $y)
{
$keys = array_keys ($x);
$values = array_values ($y);
for ($x = 0; $x < count ($keys); $x++)
{
$newarray [$keys[$x]] = $y[$keys[$x]];
}
return $newarray;
}
print_r (match_arrayKeys ($gamey, $gamex));
Output
[wow] => World greatest
[gw2] => best game
[wiz101] => WTF?
Try this
CODE
$fruits = array("d"=>"lemon", "a"=>"orange", "b"=>"banana", "c"=>"apple");
ksort($fruits);
foreach ($fruits as $key => $val) {
echo "$key = $val\n";
}
OUTPUT
a = orange
b = banana
c = apple
d = lemon
Check the php manual for ksort()