I have an array like:
Array ( [id] => 1 [code] => FAC876 )
How do I push it into another array using PHP, such that the result is like:
Array ( [0] => Array ( [id] => 1 [code] => FAC876 )
[1] => Array ( [id] => 2 [code] => GEO980 )
)
Simply threat the array as any other variable.
So if this is what you got:
$array = array();
$array1 = array( "id"=>1, "code"=>"FAC876" );
$array2 = array( "id"=>2, "code"=>"GEO980" );
You could do either
$array[] = $array1;
$array[] = $array2;
or
$array[0] = $array1;
$array[1] = $array2;
or
$array = array($array1, $array2);
or
array_push($array, $array1);
array_push($array, $array2);
Any of those four possibilites will give you what you want.
You almost posted the answer yourself:
Array (
0 => Array ( 'id' => 1, 'code' => 'FAC876' ),
1 => Array ( 'id' => 2, 'code' => 'GEO980' )
)
$arr1 = array(
'id' => 1,
'code' => 'FAC876',
);
$arr2 = array(
$arr1,
array(
'id' => 2,
'code' => 'GEO980',
),
);
or
$arr1 = array(
'id' => 1,
'code' => 'FAC876',
);
$arr2 = array(
'id' => 2,
'code' => 'GEO980',
);
$arr3 = array($arr1, $arr2);
or lots of other ways to achieve that.
$ar=array();
$ar[]=array("no"=>10,"name"=>"abc");
$ar[]=array("no"=>20,"name"=>"pqr");
$arrays = array();
$array1 = array("id" => 1, "code" => "ABC");
$array2 = array("id" => 2, "code" => "DEF");
array_push($arrays, $array1, $array2);
$array = array(array( "id"=>1, "code"=>"FAC876" ) , array( "id"=>2, "code"=>"GEO980" ));
or
$array = array();
$array[] = array( "id"=>1, "code"=>"FAC876" );
$array[] = array( "id"=>2, "code"=>"GEO980" );
or
$array = array();
array_push($array, array( "id"=>1, "code"=>"FAC876" ));
array_push($array, array( "id"=>2, "code"=>"GEO980" ));
Related
I'm needing a way to merge several arrays ( probably around 8 ) and sum any duplicate keys or sub-keys.
For example:
$arr1 = [
"Friday" => ["Breakfast" => 32, "Lunch" => 45],
"Sunday" => ["Lunch" => 12]
];
$arr2 = [
"Sunday" => ["Breakfast" => 7, "Lunch" => 3],
"Monday" => ["Breakfast" => 12]
];
$arr3 = [
"Monday" => ["Breakfast" => 31]
];
And the output should be something like this:
array (
'Friday' =>
array (
'Breakfast' => 32,
'Lunch' => 45,
),
'Sunday' =>
array (
'Lunch' => 15,
'Breakfast' => 7,
),
'Monday' =>
array (
'Breakfast' => 43,
),
);
How could I combine this? I've tried using array_map().
But that seemed to fail with multidimensional arrays like this. Also tried using foreach(), but that got pretty convoluted.
Here's my attempt:
$total = array_map( function( $arr1, $arr2, $arr3 ){
return( $arr1 + $arr2 + $arr3 );
}, $arr1, $arr2, $arr3 );
Try this solution. You can add any count of arrays. But keep names as $arr1-$maxArraysCount
$arr1 = array(
"Friday" => array(
"Breakfast" => 32,
"Lunch" => 45
),
"Sunday" => array(
"Lunch" => 12
)
);
$arr2 = array(
"Sunday" => array(
"Breakfast" => 7,
"Lunch" => 3
),
"Monday" => array(
"Breakfast" => 12
)
);
$arr3 = array(
"Monday" => array(
"Breakfast" => 31
)
);
$maxArraysCount = 8;
$return = array();
for($i = 1; $i < $maxArraysCount; $i++){
$arr = 'arr' . $i;
if(isset($$arr) && is_array($$arr)){
foreach ($$arr as $day => $value) {
foreach ($value as $eat => $count) {
if(!isset($return[$day][$eat])) $return[$day][$eat] = 0;
$return[$day][$eat] = $count + $return[$day][$eat];
}
}
}
}
echo "<pre>";print_r($return);
Here is output:
Array
(
[Friday] => Array
(
[Breakfast] => 32
[Lunch] => 45
)
[Sunday] => Array
(
[Lunch] => 15
[Breakfast] => 7
)
[Monday] => Array
(
[Breakfast] => 43
)
)
Because your data structure is fully associative, array_merge_recursive() will keep your data integrity intact. Once the arrays are merged, you only need to iterate the days' meals, cast the single values as array type (turning them into single-element arrays if not already arrays), then unconditionally all array_sum().
Code: (Demo)
$arr1 = [
"Friday" => ["Breakfast" => 32, "Lunch" => 45],
"Sunday" => ["Lunch" => 12]
];
$arr2 = [
"Sunday" => ["Breakfast" => 7, "Lunch" => 3],
"Monday" => ["Breakfast" => 12]
];
$arr3 = [
"Monday" => ["Breakfast" => 31]
];
$result = [];
foreach (array_merge_recursive($arr1, $arr2, $arr3) as $day => $meals) {
foreach ($meals as $meal => $counts) {
$result[$day][$meal] = array_sum((array)$counts);
}
}
var_export($result);
Output:
array (
'Friday' =>
array (
'Breakfast' => 32,
'Lunch' => 45,
),
'Sunday' =>
array (
'Lunch' => 15,
'Breakfast' => 7,
),
'Monday' =>
array (
'Breakfast' => 43,
),
)
To avoid variable-variables in Oleg's answer, you can stuff each of your input arrays into an array, then merge them (to preserve the duplicated day names).
Code: (Demo)
$result = [];
foreach (array_merge([$arr1], [$arr2], [$arr3]) as $array) {
foreach ($array as $day => $meals) {
foreach ($meals as $meal => $count) {
$result[$day][$meal] = ($result[$day][$meal] ?? 0) + $count;
}
}
}
or more efficiently, prepopulate the result array with your first array.
$result = $arr1;
foreach (array_merge([$arr2], [$arr3]) as $array) {
foreach ($array as $day => $meals) {
foreach ($meals as $meal => $count) {
$result[$day][$meal] = ($result[$day][$meal] ?? 0) + $count;
}
}
}
Ok the thing is, Ive read and tried a lot of solutions found here based on complete duplicateness, BUT I need something a little bit different and cant figure it out...
Because I only want to get and remove the duplicate value if only 1 of the array values is duplicate.
And also later combine the two but that's not that difficult.
$a = array(
array(
'id' => 1,
'qty' => 1
),
array(
'id' => 0,
'qty' => 1
),
array(
'id' => 1,
'qty' => 2
)
);
What I want the outcome to be:
$b = array(
array(
'id' => 1,
'qty' => 3
),
array(
'id' => 0,
'qty' => 1
)
);
You can do something like the following:
<?php
$a = array(
array(
'id' => 1,
'qty' => 1
),
array(
'id' => 0,
'qty' => 1
),
array(
'id' => 1,
'qty' => 2
)
);
$idsList = array();
$res = array();
foreach ($a as $arr){
if (!in_array($arr['id'], $idsList)){
$res[$arr['id']] = $arr;
$idsList[] = $arr['id'];
}
else{
$res[$arr['id']]['qty'] += $arr['qty'];
}
}
echo "<pre>";
print_r($res);
To get array like that:
Array
(
[1] => Array
(
[id] => 1
[qty] => 3
)
[0] => Array
(
[id] => 0
[qty] => 1
)
)
Checkout This DEMO: http://codepad.org/UP0G7WnE
$a = array(
array(
'id' => 1,
'qty' => 1
),
array(
'id' => 0,
'qty' => 1
),
array(
'id' => 1,
'qty' => 2
)
);
$b = array();
$ids = array();
for($i = 0; $i < count($a); $i++)
{
if(in_array($a[$i]['id'], $ids))
{
$j = array_search($a[$i]['id'], array_values($ids));
$b[$j]['qty'] += $a[$i]['qty'];
}
else
{
$b[$i]['id'] = $a[$i]['id'];
$b[$i]['qty'] = $a[$i]['qty'];
$ids[] = $a[$i]['id'];
}
}
echo "<pre>";
print_r($b);
This could be a solution:
$temp = array();
foreach ($a as $data){
if (isset($temp[$data['id']])){
$temp[$data['id']] += $data['qty'];
} else {
$temp[$data['id']] = $data['qty'];
}
}
// Format array
$b = array();
foreach ($temp as $id => $qty){
$b[] = array(
'id' => $id,
'qty' => $qty
);
}
Output will be:
Array
(
[0] => Array
(
[id] => 1
[qty] => 3
)
[1] => Array
(
[id] => 0
[qty] => 1
)
)
I have an array as such:
[0] => Array
(
[0] => 1
[1] => 30
[2] => 33
)
[1] => Array
(
[id] => 5
)
I want to move all values in the [0] index out so they become part of the parent array. So the final outcome would look like such:
[0] => Array
(
[id] => 1
)
[1] => Array
(
[id] => 30
)
[2] => Array
(
[id] => 33
)
[3] => Array
(
[id] => 5
)
As you can see the numerical indexes on [0] have now changed to id
I've tried using array_map('current', $array[0])
to no avail, any suggestions?
You could use the ol' trusty double foreach:
$new_array = array();
foreach ($array as $arr) {
foreach ($arr as $ar) {
$new_array[] = array('id'=>$ar);
}
}
Demo
$data = array(
array(1, 30, 33),
array('id' => 5)
);
$result = array();
array_walk_recursive(
$data,
function($value) use (&$result) {
$result[] = array('id' => $value);
}
);
var_dump($result);
Just to show that iterators can be really useful tools as well:
$data = array(
array(1, 30, 33),
array('id' => 5)
);
$result = array();
foreach (new RecursiveIteratorIterator(
new RecursiveArrayIterator($data),
RecursiveIteratorIterator::LEAVES_ONLY
) as $value) {
$result[] = array('id' => $value);
}
var_dump($result);
$array = [
[1, 30, 33],
['id' => 5]
];
$result = array_reduce($array, function (array $result, array $array) {
return array_merge($result, array_map(
function ($id) { return compact('id'); },
array_values($array)
));
}, []);
var_dump($result);
Admittedly not the simplest way to solve this, but very "functional". ;)
$array = array(
array(0 => 1,1 => 30,2 => 33,),
array("id" => 5,)
);
$result = array_merge(
array_map('array_flip',
array_chunk(
array_fill_keys($array[0], "id"),
1, true)
),
array_slice($array, 1)
);
var_export($result);
Results in:
array (
array ( 'id' => 1 ),
array ( 'id' => 30 ),
array ( 'id' => 33 ),
array ( 'id' => 5 )
)
I have this array. How do I remove all those elements which are present in another array i.e. $remove and re-index the final array starting from 1 not 0?
$info = array(
'1' => array('name' => 'abc', 'marks' => '56'),
'2' => array('name' => 'def', 'marks' => '85'),
'3' => array('name' => 'ghi', 'marks' => '99'),
'4' => array('name' => 'jkl', 'marks' => '73'),
'5' => array('name' => 'mno', 'marks' => '59')
);
$remove = array(1,3);
Desired Output:
$info = array(
'1' => array('name' => 'def', 'marks' => '85'),
'2' => array('name' => 'jkl', 'marks' => '73'),
'3' => array('name' => 'mno', 'marks' => '59')
);
So far I've tried these two methods. Nothing worked for me.
if (($key = array_search(remove[0], $info))) {
unset($info[$key]);
$info = array_values($info);
}
And
$result = array_diff($info, $remove);
Something like this will work:
$result = array_diff_key( $info, array_flip( $remove));
This array_flip()s your $remove array so the keys become the values and the values becomes the keys. Then, we do a difference against the keys with array_diff_key() of both arrays, to get this result:
Array
(
[2] => Array
(
[name] => def
[marks] => 85
)
[4] => Array
(
[name] => jkl
[marks] => 73
)
[5] => Array
(
[name] => mno
[marks] => 59
)
)
Finally, to yield your exact output, you can reindex your array by passing it through array_values(), but this will yield sequential indexes starting at zero, not one:
$result = array_values( array_diff_key( $info, array_flip( $remove)));
If you really need indexes to start at one, you will need a combination of array_combine() and range():
$result = array_diff_key( $info, array_flip( $remove));
$result = array_combine( range( 1, count( $result)), $result);
What about using array_diff function?
Example
$array1 = array("a" => "green", "red", "blue", "red");
$array2 = array("b" => "green", "yellow", "red");
$result = array_diff($array1, $array2);
print_r($result);
this will output
Array
(
[1] => blue
)
How do I write PHP code to manually create this array?
Array (
[0] => Array
(
[Id] => 2
[Fruit] => Apple
)
[1] => Array
(
[Id] => 5
[Fruit] => Orange
)
)
$arr = array();
$arr[] = array("Id" => 2, "Fruit" => "Apple");
$arr[] = array("Id" => 5, "Fruit" => "Orange");
$array = array();
$array[] = array(
'id'=>3,
'Fruit'=>'Orange'
);
$array[] = array(
'id'=>7,
'Fruit'=>'Banana'
);
$array =array(
array('Id'=>2, 'Fruit'=>'Apple'),
array('Id'=>5, 'Fruit'=>'Orange')
);
NB: array keys are case-sensitive.