Create multidimensional array from multiple arrays in PHP [duplicate] - php

This question already has answers here:
Merge two arrays as key value pairs in PHP
(3 answers)
Closed 5 months ago.
I have two arrays:
Array ( [0] => label [1] => data )
Array ( [0] => 1 [1] => 2 )
And I need merge them in a array like this:
Array ( [0] => Array ( [label] => 1 [data] => 2 ) )
I have tried:
for ($i=0; $i < count($inputs); $i++) {
$new = array($cols[$i] => $inputs[$i]);
$data[] = $new;
}
Any help is welcome ;)

You can simply use array_combine:
Creates an array by using one array for keys and another for its
values
$arr1 = array(0 => 'label', 1 => 'data');
$arr2 = array(0 => 1, 1 => 2);
$arr3 = array_combine($arr1, $arr2);
print_r($arr3);
Result:
Array
(
[label] => 1
[data] => 2
)
Try it

You can do it like so if you want to use a loop
$array1 = ['label', 'data'];
$array2 = [1, 2];
$array_merged = [];
foreach($array1 as $key => $value) {
$array_merged[$value] = $array2[$key];
}
var_dump($array_merged);
http://sandbox.onlinephpfunctions.com/code/c4e5bc71df53ebdafb0a54d43c3eadb4ea4cd241

Related

Two dimentional array into single dimentional array without foreach PHP [duplicate]

This question already has answers here:
How to Flatten a Multidimensional Array?
(31 answers)
Closed 4 years ago.
Is there way to convert two dimentional array into single dimentional array without using foreach loop in php.
Below is the actual array
Array
(
[0] => Array
(
[male] => male
[female] => female
)
[1] => Array
(
[male] => male1
[female] => female1
)
)
And Output will be like
Array
(
[0] = > male
[1] = > female
[2] = > male1
[3] = > female1
)
You can use reduce and use array_merge
$array = array( ... ); //Your array here
$result = array_reduce($array, function($c,$v){
return array_merge(array_values($c),array_values($v));
}, array());
This will result to:
Array
(
[0] => male
[1] => female
[2] => male1
[3] => female1
)
This loops through your multidimensional array and stores the results in the new array variable $newArray.
$newArray = array();
foreach($multi as $array) {
foreach($array as $k=>$v) {
$newArray[$k] = $v;
}
}

Remove duplicate array on the base of key in multidimendional array PHP [duplicate]

This question already has answers here:
How to remove duplicate values from a multi-dimensional array in PHP
(18 answers)
Closed 6 years ago.
From following array key with ID 16 is comming twice. Hown can we remove this this duplicate ID. (REMOVE IF ID IS DUPLICATE OTHER FIELDS IGNORE)
Array
(
[1] => Array
(
[ID] => 16
[username] => dudda
[message-time] => 2016-08-25 12:12:53
)
[2] => Array
(
[ID] => 16
[username] => dudda
[message-time] => 2016-08-25 12:01:54
)
[3] => Array
(
[ID] => 3
[username] => himanshu
[message-time] => 2016-08-15 12:53:38
)
[4] => Array
(
[ID] => 15
[username] => dawinder
[message-time] => 2016-08-10 11:40:33
)
)
I Got solution
I have develop this function for same :
function unique_multidim_array($array, $key) {
$temp_array = array();
$i = 0;
$key_array = array();
foreach($array as $val) {
if (!in_array($val[$key], $key_array)) {
$key_array[$i] = $val[$key];
$temp_array[$i] = $val;
}
$i++;
}
return $temp_array;
}
Now, call this function anywhere from your code,
something like this,
$details = unique_multidim_array($array_name,'key');
We used this to de-duplicate results from a variety of overlapping queries.
$input = array_map("unserialize", array_unique(array_map("serialize", $input)));
array array_unique ( array $array [, int $sort_flags = SORT_STRING ] )
Read this:http://php.net/manual/en/function.array-unique.php
For Example
<?php
$input = array("a" => "green", "red", "b" => "green", "blue", "red");
$result = array_unique($input);
print_r($result);
?>
Output will be:
Array
(
[a] => green
[0] => red
[1] => blue
)

Combine two different dimensional arrays PHP

I have two different dimensional arrays.
Array 1:
Array1
(
[0] => Array
(
[id] => 123
[price] => 5
[purchase_time] => 2014/4/10
)
[1] => Array
(
[id] => 123
[price] => 5
[purchase_time] => 2014/5/17
)
)
Array 2:
Array2
(
[0] => 5
[1] => 8
)
I want something like this:
Array
(
[0] => Array
(
[id] => 123
[price] => 5
[purchase_time] => 2014/4/10
[Qty] => 5
)
[1] => Array
(
[id] => 123
[price] => 5
[purchase_time] => 2014/5/17
[Qty] => 8
)
)
Basically the first array is the information I got from a SQL table. The second array contains the quantity for the products sold. I now want to combine these two array together and use the combined array to create a new table. Since these two arrays have different dimensions. I'm not sure how to do it. Here is my try:
$i = 0;
foreach($array1 as $row)
{
$newarray = array_merge($row,$array2[$i]);
$i++;
}
Might be a simpler way, but for fun without foreach:
array_walk($array1, function(&$v, $k, $a){ $v['Qty'] = $a[$k]; }, $array2);
The simplest way is:
$i = 0;
foreach($array1 as &$row) {
$row['Qty'] = $array2[$i++];
}
Or if keys of both arrays are the same (0,1,2...) and array have the same length:
foreach($array1 as $k => &$row) {
$row['Qty'] = $array2[$k];
}
If the $array1 and $array2 are mapped by the same indexes, so they have same length, you can try:
foreach($array2 as $index=>$quantity){
$array1[$index]['Qty'] = $quantity;
}
And it´s done!
If you want to keep the original $array1 untouched, you can make a copy before the foreach.
Create new array and store it there. You can access the value of $array2 because they have the same index of $array1 so you can use the $key of these two arrays.
$array3 = [];
foreach($array1 as $key => $val) {
$array3[] = [
'id' => $val['id'],
'price' => $val['price'],
'purchase_time' => $val['purchase_time'],
'Qty' => $array2[$key]
];
}
print_r($array3);

Concatenate values of two arrays [duplicate]

This question already has answers here:
Cartesian Product of N arrays
(10 answers)
Closed 8 years ago.
Let's assume I have an two arrays and I want to merge every value with the other value of the array.
Array 1
array (size=2)
0 => 1
1 => 2
Array 2
array (size=2)
0 => 3
1 => 4
Wanted result array / string:
array (size=4)
0 => '1,3'
1 => '1,4'
2 => '2,3'
3 => '2,4'
I can't get my head around it. Obviously I would need to merge every one array key/value with the other ones. Is there a more elegant way then doing this in a while/foreach loop?
You need a foreach loop inside a foreach loop. (Actualy, you will have to loop through both arrays to get a concatenated product of both arrays, you don't actually need two foreach loops). You could mix: whiles, foreach, for, or php filter/intersect array functions
Example
$array1 = array(1,2);
$array2 = array(3,4);
$result = array();
foreach ($array1 as $item1){
foreach($array2 as $item2){
$result[] = $item1.','.$item2;
}
}
https://eval.in/215001
your result array Length will be array1.Length * array2.Length
2d arrays
You could also put an array inside an array like this:
$array1 = array(1,2);
$array2 = array(3,4);
$result = array();
foreach ($array1 as $item1){
foreach($array2 as $item2){
$result[] = array($item1, $item2);
}
}
//$result[0][0] = 1 -- $result[0][1] = 3
//$result[1][0] = 1 -- $result[1][1] = 4
//$result[2][0] = 2 -- $result[2][1] = 3
//$result[3][0] = 2 -- $result[3][1] = 4
We call this a 2d (2 dimensional) array, because you could grapicly display this as a grid, like displayed here above. If you would put an Array, inside an Array inside an Array, you would call this a 3 dimensional array, etc.
print_r($result); in php:
Array
(
[0] => Array
(
[0] => 1
[1] => 3
)
[1] => Array
(
[0] => 1
[1] => 4
)
[2] => Array
(
[0] => 2
[1] => 3
)
[3] => Array
(
[0] => 2
[1] => 4
)
)
try
$a= array ('0' => 1,'1' => 2);
$b= array ('0' => 3,'1' => 4);
for($i=0; $i<count($a); $i++) {
for($j=0; $j<count($b); $j++) {
$newarr[]= $a[$i].','.$b[$j];
}
}
print_r($newarr);//Array ( [0] => 1,3 [1] => 1,4 [2] => 2,3 [3] => 2,4 )
$a=array('1','2');
$b=array('3','4');
$res=array();
for($i=0;$i<count($a);$i++)
{
foreach($b as $bb)
{
$res[]=strval($a[$i].','.$bb);
}
}
print_r($res);//output=Array ( [0] => 1,3 [1] => 1,4 [2] => 2,3 [3] => 2,4 )

Merging two assosiative arrays in php?

I have two associative arrays.
array ( [apple]=>1 [banana]=>2 cocunet => 3)
and other array is
array ( [apple]=>2 [banana]=>3 cocunet => 4)
now i want to merge my array like that
array ( [apple]=>1,2 [banana]=>2,3 cocunet => 3,4)
There is no such array in PHP. The thing you want can only be done by creating multidimentional arrays.
$a1 = array( 'apple'=>1,'banana'=>2,'coconut'=> 3);
$a2 = array( 'apple'=>2,'banana'=>3,'coconut'=> 4);
echo "<pre>";
print_r(array_merge_recursive($a1,$a2));
echo "</pre>";
For this you can use the array_merge_recursive() function.
PHPFiddle: http://3v4l.org/5OCKI
If you want the result to be a string then this should work:
foreach( $array_1 as $fruit => $num) {
if(array_key_exists($fruit, $array_2)){ //check if key from array_1 exists in array_2
$final_array[] = array($fruit => $array_1[$fruit].','.$array_2[$fruit]); //concatenate values from shared key
}
}
print_r($final_array) will return:
Array
(
[0] => Array
(
[apple] => 1,2
)
[1] => Array
(
[banana] => 2,3
)
[2] => Array
(
[coconut] => 3,4
)
)
<?php
$array1 = array("apple" => 5, "banana" => 1);
$array2 = array("banana" => 4, "coconut" => 6);
print_r( array_merge_recursive( $array1, $array2 ) );
?>
Returns:
Array ( [apple] => 5 [banana] => Array ( [0] => 1 [1] => 4 ) [coconut] => 6 )
I only used two elements in each of the primary arrays to demonstrate the output prior to having any groups existing, i.e. non-array value.

Categories