merge two associative arrays in one associative array - php

I want to merge many different assoc arrays in one array but in the form of assoc array. Like i have different arrays like this
Array ( [0] => abc [1] => def [2] => ghi )
Array ( [0] => jkl [1] => mno [2] => pqr )
.
.
.
and want to make an array like
array
0 =>
array
0 => string 'abc'
1 => string 'def'
2 => string 'ghi'
1 =>
array
0 => string 'jkl'
1 => string 'mno'
2 => string 'pqr'
.
.
.`
.
i am getting these arrays from a csv file. Please help. Thanks

If I understand correctly, you don't want to merge the arrays... you just want to make a multidimensional array i.e. an array of arrays. See the difference here.
You are creating the initial arrays from the csv file, but I'll create them here for completeness:
$array1 = array ( "0" => "abc", "1" => "def", "2" => "ghi" );
$array2 = array ( "0" => "jkl", "1" => "mno", "2" => "pqr" );
Then all you need to do is create an array with those arrays as the values, depending on what works with the rest of your code, e.g.
$multiarray = array();
$multiarray["0"] = $array1;
$multiarray["1"] = $array2;
or
$multiarray = array ( "0" => $array1, "1" => $array2 );
If you print_r ($multiarray);, it will look like the example in your question.
By the way, the examples you have given are not associative arrays, but I've treated them as if they are in case you do actually need them.
If your arrays are just standard indexed arrays, then you don't need to specify the key, e.g.
$array1 = new array("abc", "def", "ghi");
etc
$multiarray[] = $array1;
$multiarray[] = $array2;

I provide another point of view, which is lest optimized for the task in itself as I see it but might be useful in some context.
$array = array('abc', 'def', 'ghi');
$array2 = array('jkl', 'mno', 'pqr');
function gather(... $array){return $array;}
my_print_r(gather($array, $array2));
That function uses the splat operator, which natively gathers whatever arguments are sent to the function as entries in an array, called array in that example. We can do whatever we want with array in that function, but just by retuning it, it does what you asked for.

Related

How to combaine multiple array to one array

I want to need multiple array combaine in one array
I have array
array(
0=> test 1
)
array(
0=> test 2
)
array(
0=> test 3
)
I need expected output
`array(
0=>Test1
1=>Test2
2=>test3
)`
You can use the array_merge() for this. The array_merge() function merges one or more arrays into one array.If two or more array elements have the same key, the last one overrides the others.
Syntax:
array_merge(array ...$arrays): array
Example:
$a1=array("red","green");
$a2=array("blue","yellow");
print_r(array_merge($a1,$a2));
Result:
Array ( [0] => red [1] => green [2] => blue [3] => yellow )
You can check more here.
$a = array('test_1');
$b = array('test_2');
$c = array('test_3');
print_r(array_merge($a,$b,$c));
O/P - Array ( [0] => test_1 [1] => test_2 [2] => test_3 )
Hope you are doing well and good.
So, as per your requirement i found solution to get result.
$array1 = [0 => "Test 1"]; $array2 = [0 => "Test 2"]; $array3 = [0 => "Test 3"];
print_r(array_merge($array1,$array2,$array3));
In the above example you have to merge the n number of array with single array, so for that you need to use array function which is array_merge(array ...$array).
What is array_merge()?
The array_merge() function merges one or more arrays into one array.
Tip: You can assign one array to the function, or as many as you like.
Note: If two or more array elements have the same key, the last one overrides the others.

How to extract the keys of an Array and push them to a String array?

Everyone else usually asking how to convert string array with commas to an array of key value pairs.
But my question is opposite. I want to extract the keys of the array and place them in a separate array using PHP
I have an array of this form:
Array
(
[Lights] => 4
[Tool Kit] => 4
[Steering Wheel] => 4
[Side Mirrors] => 3.5
)
and I want output to be in this form:
{"Lights", "Tool Kit", "Steering Wheel", "Side Mirrors" }
Using array_keys :
array_keys — Return all the keys or a subset of the keys of an array
So you can just extract each keys simply by using this method
$keys = array_keys($array);
Otherwise, you can loop through each values and only get the keys :
$keyArray=array_keys($array);
$keyArray=[];
foreach($array as $key => $value){
$keyArray[]=$key;
}
Use array_keys. It will return array keys as array values
$array=array('Lights' => 4,
'Tool Kit' => 4,
'Steering Wheel' => 4,
'Side Mirrors' => 3.5);
$key_array=array_keys($array);
print_r($key_array);
It will result
Array ( [0] => Lights [1] => Tool Kit [2] => Steering Wheel [3] => Side Mirrors )
Looks like you are expecting JSON output. You can just use json_encode function in a pair with array_keys.
$result = json_encode(array_keys($array));
However, your result will be ["Lights","Tool Kit","Steering Wheel","Side Mirrors"]

Is array_merge perform reindexing?

Suppose I have an associative array with keys that are alphabetic string, and if I merge something to this array, It will merge successfully without reindexing like
$arr1 = array('john'=>'JOHN', 'marry'=>'Marry');
$arr1 = array_merge(array('78'=>'Angela'),$arr1);
print_r($arr1);
then this will correctly merge new component to array and its output will be
Array
(
[0] => Angela
[john] => JOHN
[marry] => Marry
)
But when I tried same thing like this
$arr1 = array('34'=>'JOHN', '04'=>'Marry');
$arr1 = array_merge(array('78'=>'Angela'),$arr1);
print_r($arr1);
then its output is like this
Array
(
[0] => Angela
[1] => JOHN
[04] => Marry
)
Can anyone describes this scenario.....
Also I want my array to be like this after merging..
Array
(
[78] => Angela
[34] => JOHN
[04] => Marry
)
How can I Achieve that??
as per definition array_merge will reindex numeric indexes. a string with a numeric value is also a numeric index.
To prevent this behaviour concatenate the arrays using $arr1+$arr2
You don't need to use array_merge() as you can simply add the arrays:
$arr1 = [
'10' => 'Angela',
'john' => 'JOHN',
'marry' => 'Marry',
];
$arr2 = [
'78' => 'Angela'
];
$arr3 = $arr2 + $arr1;
array_merge() - ... values in the input array with numeric keys will be renumbered with incrementing keys starting from zero in the result array.

php assoc array

I have two assoc array i want to creat one array out of that
E.g
a(a=>1
b=>3
f=>5
)
b(a=>4
e=>7
f=>9
)
output must be
c(
a=>1
b=>3
f=>5
a=>4
e=>7
f=>9
)
i am new in php
Use array_merge(). Your resulting array CAN NOT have more than one entry for the same key, so the second a => something will overwrite the first.
Use the + operator to return the union of two arrays.
The new array is constructed from the left argument first, so $a + $b takes the elements of $a and then merges the elements of $b with them without overwriting duplicated keys. If the keys are numeric, then the second array is just appended.
This ey difference of the + operator and the function, array_merge is that array merge overwrites duplicated keys if the latter arguments contain that key. The documentation puts it better:
If the input arrays have the same string keys, then the later value for that key will overwrite the previous one. If, however, the arrays contain numeric keys, the later value will not overwrite the original value, but will be appended.
If the keys are different, then use array_merge()
<?php
$a1=array("a"=>"Horse","b"=>"Cat");
$a2=array("c"=>"Cow");
print_r(array_merge($a1,$a2));
?>
OUTPUT:
Array ( [a] => Horse [b] => Cat [c] => Cow )
If the keys are the same, then use array_merge_recursive()
<?php
$ar1 = array("color" => array("favorite" => "red"), 5);
$ar2 = array(10, "color" => array("favorite" => "green", "blue"));
$result = array_merge_recursive($ar1, $ar2);
print_r($result);
?>
OUTPUT:
Array
(
[color] => Array
(
[favorite] => Array
(
[0] => red
[1] => green
)
[0] => blue
)
[0] => 5
[1] => 10
)

I am so confused with associative arrays in php (two and 3 dimensional)

I am learning php. In spite of so many examples on google, I am still confused about implementing arrays which are two dimensional and three dimensional. Can anyone explain, in simple terms, with an example please?
The easiest example for me was thinking of a SQL table as a multidimensional array.
The table might look like this:
ID | Name | Email
--------------------------
1 | John | john#email.com
2 | Jane | jane#email.com
And the array might look like this:
Array
(
[0] => Array
(
[0] => 1
[1] => John
[2] => john#email.com
)
[1] => Array
(
[0] => 2
[1] => Jane
[2] => jane#email.com
)
)
The table is turned into an array of arrays. Where each row is accessed by the first index and each column by the second index.
So If I wanted to get "Jane" I would use $array[1][1]
An associative array of that same table might look like this:
Array
(
[0] => Array
(
[ID] => 1
[Name] => John
[Email] => john#email.com
)
[1] => Array
(
[ID] => 2
[Name] => Jane
[Email] => jane#email.com
)
)
You would access "Jane" like $array[1]["Name"]
These are arrays which are nested in other arrays. Depending on how deep they are nested determines what dimensional they are.
Here is an example of a 1D and 2D array, respectively.
$arr =
array(
'item1' => 543,
654 => true,
'xas' => 0.54
);
// Accessing $arr[654] (returns true)
$arr2 = array(
array
(
'a' => 54,
'b' => 'Hello'
),
array
(
'itemx' => true,
954 => 'hello'
)
);
// Accessing $arr[0]['b'] (equal to 'Hello')
For a 3D array, you simply add another nested array into one of the 2nd level array items in the 2D array example.
There also is a very simple way to get started with multidimensional arrays.
Simply take a sheet and a pencil and start writing your multidimensional array down on paper first. It will help you a lot in the beginning.
It should look something like this.
ARRAY0 {
key0.0 => "value0.0",
key0.1 => "value0.1",
key0.2 => ARRAY1 {
key1.0 => "value1.0",
key1.1 => ARRAY2 {
key2.0 => "value2.0",
key2.1 => "value2.1",
},
key1.2 => "value1.2",
},
key0.3 => "value0.3",
};
This is just my way of visualizing the arrays you can come up with your own syntax if you want.
An array can have anything in it, from an integer to a string, to a full blown object, to another array.
Any array on its own is called a 1-dimensional array. If you think of it as a row of boxes, then it's a single row. If an array has another array in it then it's a 2-dimensional array: one of its boxes will be a column, adding another dimension.
$users = array() ;
$jim = array('Jim', 'Smith') ;
$users[] = $jim ;
//or in one step
$users = array(array('Jim', 'Smith')) ;
//then to access the first user:
$jim = $users[0];
//and his firstname:
$jimsname = $users[0][0] ;
//or
$jimsname = $jim[0] ;
You can access elements of the array and its nested arrays by indices, but you need to remember which numeric index corresponds to which piece of information. That's where you can use associative arrays, where the numeric indices are replaced by unique descriptive strings:
$users = array() ;
$jim = array(
'firstname' => 'Jim',
'lastname' => 'Smith'
) ;
$users['jim'] = $jim ;
//then to access jim:
$jim = $users['jim'];
//and his firstname:
$jimsname = $users['jim']['firstname'] ;
//or
$jimsname = $jim['firstname'] ;
That's pretty much it. You can see more here and in the manual
try this simply.
$anArray['abc'][1]['qwe']='this is a value';
$anArray['abc']['avs']='another value';
echo $anArray['abc'][1]['qwe'];
echo $anArray['abc']['avs'];
/*
Array is a bit different in PHP. You can think of array elements as single variables ($anArray['abc'][1]['qwe'] or $anArray['abc']['avs']). And you can create them like single variables. This is an addition to conventional arrays. Conventional way is also supported.
But what happens if you write : $anArray['abc']='something else';
$anArray['abc'] is just a string variable from that point. So you cannot (or may not as I didn't test it yet and practically everything is possible) access $anArray['abc'][1]['qwe'] anymore.
So try to think the elements like variables, first ;)
*/

Categories