This question may sound silly, but I didn't find a good approach.
I have to multidimensional arrays like this:-
array
(
[0] => Array
(
[field1] => A
[field2] => 100
[field3] => 20
)
[1] => Array
(
[field1] => B
[field2] => 100
[field3] => 30
)
[2] => Array
(
[field1] => C
[field2] => 100
[field3] => 30
)
)
array
(
[0] => Array
(
[field1b] => A
[field2b] => 500
[field3b] => 0
)
[1] => Array
(
[field1b] => B
[field2b] => 300
[field3b] => 10
)
)
I want to merge both arrays using field1 as Key, and having in mind that arrays aren't same size.
The result array should be:
array
(
[0] => Array
(
[field1] => A
[field2] => 100
[field3] => 20
[field2b] => 500
[field3b] => 0
)
[1] => Array
(
[field1] => B
[field2] => 100
[field3] => 30
[field2b] => 300
[field3b] => 10
)
[2] => Array
(
[field1] => C
[field2] => 100
[field3] => 30
)
)
Thanks in advance!
Try this,
$array1 = array
(
"0" => Array
(
"field1" => "A",
"field2" => "100",
"field3" => "20"
),
"1" => Array
(
"field1" => "B",
"field2" => "100",
"field3" => "30"
),
"2" => Array
(
"field1" => "C",
"field2" => "100",
"field3" => "30"
)
);
$array2 = array
(
"0" => Array
(
"field1b" => "A",
"field2b" => "500",
"field3b" => "0"
),
"1" => Array
(
"field1b" => "B",
"field2b" => "300",
"field3b" => "10"
)
);
foreach($array1 as $key=>$val)
{
$new_array[$key]['field1'] = $val['field1'];
$new_array[$key]['field2'] = $val['field2'];
$new_array[$key]['field3'] = $val['field3'];
if (array_key_exists($key,$array2))//Check if the key is exists in an array
{
$new_array[$key]['field2b'] = $array2[$key]['field2b'];
$new_array[$key]['field3b'] = $array2[$key]['field3b'];
}
}
echo "<pre>";
print_r($new_array);
echo "</pre>";
DEMO
Very simple:- apply foreach and do it like below:-
<?php
$final_array = array();
foreach ($arr1 as $key=>$val){
if(isset($arr2[$key])){
$final_array[$key] = array_merge($val,$arr2[$key]);
unset($final_array[$key]['field1b']);
}else{
$final_array[$key] = $val;
}
}
echo "<pre/>";print_r($final_array);
Output:- https://eval.in/661803
If your both array have different number of elements then :-
<?php
$count1 = count ($arr1);
$count2 = count ($arr2);
$final_array = array();
if ($count1 >$count2){
foreach ($arr1 as $key=>$val){
if(isset($arr2[$key])){
$final_array[$key] = array_merge($val,$arr2[$key]);
unset($final_array[$key]['field1b']);
}else{
$final_array[$key] = $val;
}
}
echo "<pre/>";print_r($final_array);
}else if ($count2 >$count1){
foreach ($arr2 as $key=>$val){
if(isset($arr1[$key])){
$final_array[$key] = array_merge($val,$arr1[$key]);
unset($final_array[$key]['field1b']);
}else{
$final_array[$key] = $val;
}
}
echo "<pre/>";print_r($final_array);
}else{
foreach ($arr1 as $key=>$val){
if(isset($arr2[$key])){
$final_array[$key] = array_merge($val,$arr2[$key]);
unset($final_array[$key]['field1b']);
}else{
$final_array[$key] = $val;
}
}
echo "<pre/>";print_r($final_array);
}
<?php
$array1 = array
(
"0" => Array
(
"field1" => "A",
"field2" => "100",
"field3" => "20"
),
"1" => Array
(
"field1" => "B",
"field2" => "100",
"field3" => "30"
),
"2" => Array
(
"field1" => "C",
"field2" => "100",
"field3" => "30"
)
);
$array2 = array
(
"0" => Array
(
"field1b" => "A",
"field2b" => "500",
"field3b" => "0"
),
"1" => Array
(
"field1b" => "B",
"field2b" => "300",
"field3b" => "10"
)
);
$new_array1 = [];
foreach ($array1 as $object1) {
$new_array1[$object1['field1']] = $object1;
}
$new_array2 = [];
foreach ($array2 as $key => $object2) {
$new_array2[$object2['field1b']] = $object2;
}
$new_array = [];
foreach($new_array1 as $key => $val)
{
$new_array[$key]['field1'] = $val['field1'];
$new_array[$key]['field2'] = $val['field2'];
$new_array[$key]['field3'] = $val['field3'];
if (array_key_exists($key,$new_array2))//Check if the key is exists in an array
{
$new_array[$key]['field2b'] = $new_array2[$key]['field2b'];
$new_array[$key]['field3b'] = $new_array2[$key]['field3b'];
}
}
print_r($new_array);
DEMO
You can try it.
What about this instead defining hard-coded keys condition? all you need is to provide the key which should not be included in combined array..
Demo
<?php
$A = array(
array(
'field1' => 'A',
'field2' => '100',
'field3' => '20',
),
array(
'field1' => 'B',
'field2' => 100,
'field3' => 30,
),
array(
'field1' => 'C',
'field2' => 100,
'field3' => 30,
)
);
$B = array(
array(
'field1b' => 'A',
'field2b' => 500,
'field3b' => 0
),
array(
'field1b' => 'B',
'field2b' => 300,
'field3b' => 10
)
);
$combined = array();
foreach($A as $key => $arr) {
$tempKey = reset($arr);
$second_arr = $B[ $key ];
$tempKey2 = reset($B[ $key ]);
if( $tempKey == $tempKey2 ) {
$combined[] = $arr + $second_arr;
unset( $combined[ $key ]['field1b'] );
}
else {
$combined[] = $arr;
}
}
echo '<pre>';
print_r($combined);
echo '</pre>';
Related
I have an array looks like this:
Array
(
[0] => Array
(
[name] => color
[value] => red
)
[1] => Array
(
[name] => shape
[value] => square
)
[2] => Array
(
[name] => price
[value] => $15
)
)
I want to have a result like this:
$myArr = array (
'color' => 'red',
'shape' => 'square',
'price' => '$15'
)
I have tried to loop but can not get it to work.
foreach($myArr as $id => $values){
foreach ($values as $key => $value) {
if($key == 'name') {
//add to array key
} else {
//add to that array key value
}
}
}
hope you guys can help me with solution.
You can use array_column and array_combine
$arr = array(
array("name" => 'color',"value" => 'red'),
array("name" => 'shape',"value" => 'square'),
array("name" => 'price',"value" => '$15')
);
$newArr = array_combine(array_column($arr,'name'),array_column($arr,'value'));
echo "<pre>";
print_r( $newArr );
echo "</pre>";
This will result to:
Array
(
[color] => red
[shape] => square
[price] => $15
)
Doc: array_column, array_combine
$a = [
0 => [
"name" => "color",
"value" => "red",
],
1 => [
"name" => "shape",
"value" => "square",
],
2 => [
"name" => "price",
"value" => "$15",
]
];
$b = [];
foreach($a as $v)
{
$b[$v["name"]] = $v["value"];
}
var_dump($b);
result
array(3) {
["color"]=>
string(3) "red"
["shape"]=>
string(6) "square"
["price"]=>
string(3) "$15"
}
$arr = array
(
0 => array
(
'name' => 'color',
'value' => 'red'
),
1 => array
(
'name' => 'shape',
'value' => 'square'
),
2 => array
(
'name' => 'price',
'value' => '$15'
)
);
$final_array =[];
foreach($arr as $key=> $val){
$final_array[$val['name']] = $val['value'];
}
echo "<pre>"; print_r($final_array);
I have data below :
Array(
[A] => Array
(
[AA] => 10
)
[B] => Array
(
[BA] => 5
[BB] => 1
[BC] => -2
)
[C] => Array
(
[CA] => 3
[CB] => 0
)
)
I want to sum the value of second element my array (BA,BB,BC, etc) like this :
Array(
[A] => 10
[B] => 4
[C] => 3
)
I've tried to do with foreach (I'm using php as my platform) but the result is wrong, can someone give me explanation and the logic to solve this? thanks
You can loop thru your array and use array_sum
$arr = array(
"A" => array
(
"AA" => 10,
),
"B" => array
(
"BA" => 5,
"BB" => 1,
"BC" => -2
),
"C" => array
(
"CA" => 3,
"CB" => 0
)
);
$result = array();
foreach( $arr as $key => $val ){
$result[$key] = array_sum ( $val );
}
echo "<pre>";
print_r( $result );
echo "</pre>";
This will result to:
Array
(
[A] => 10
[B] => 4
[C] => 3
)
Doc: http://php.net/manual/en/function.array-sum.php
This should work for arrays like the one of your example:
$arr = array(
"A" => array
(
"AA" => 10,
),
"B" => array
(
"BA" => 5,
"BB" => 1,
"BC" => -2
),
"C" => array
(
"CA" => 3,
"CB" => 0
)
);
$res = array();
foreach($arr as $key => $value) {
foreach($value as $number) {
(!isset($res[$key])) ?
$res[$key] = $number :
$res[$key] += $number;
}
}
echo "<pre>";
print_r( $res );
echo "</pre>";
This is working without using an inbuilt function.
if you want sum column
<?php
$array = array
(
"A"=>array
(
"AA" => 10,
),
"B"=>array
(
"BA" => 5,
"BB" => 1,
"BC" => -2
),
"C"=>array
(
"CA" => 3,
"CB" => 0
)
);
foreach ($array as $key=>$value)
{
$mehrdad[]=$key;
}
foreach ($mehrdad as $key1=>$value1)
{
$arrays=$array[$value1];
foreach ($arrays as $key2=>$value2)
{
$mehrdadi[]=$key2;
}
}
$mehrdadend=array_unique($mehrdadi);
$mehrdadis = array();
foreach ($mehrdadend as $key3=>$value3)
{
$sum=array_sum(array_column($array, $value3));
$mehrdadis[$value3] = $sum;
}
print_r($mehrdadis);
?>
Result
Array
(
[AA] => 10
[BA] => 5
[BB] => 1
[BC] => -2
[CA] => 3
[CB] => 0
)
I have an array $array1 with different amount of key and value pairs:
Array
(
[0] => Array
(
[ID] => 39
[title] => Apple
)
[1] => Array
(
[ID] => 40
[title] => Orange
)
)
and another array $array2:
Array
(
[0] => 273
[1] => 386
)
And I want to get this:
Array
(
[0] => Array
(
[ID] => 39
[title] => Apple
[pages] => 273
)
[1] => Array
(
[ID] => 40
[title] => Orange
[pages] => 386
)
)
The number of items in each array is the same and the correspond, so, we don't need to check this, so, how to merge it like that?
use array_replace_recursive if you want merge with integer keys, or array_merge_recursive if you want merge only string keys
<?php
$a1 = array(
0 => array
(
"ID" => 39,
"title" => "Apple"
),
1 => array(
"ID" => 40,
"title" => "Orange"
)
);
$a2 = array(
0 => array
(
"pages" => 273,
"year" => 1981
),
1 => array(
"pages" => 386,
"year" => 1979
)
);
$a3 = array_replace_recursive($a1, $a2);
var_dump($a3);
Result:
array(2) {
[0] =>
array(4) {
'ID' =>
int(39)
'title' =>
string(5) "Apple"
'pages' =>
int(273)
'year' =>
int(1981)
}
[1] =>
array(4) {
'ID' =>
int(40)
'title' =>
string(6) "Orange"
'pages' =>
int(386)
'year' =>
int(1979)
}
}
Answer for updated question:
<?php
$a1 = array(
0 => array
(
"ID" => 39,
"title" => "Apple"
),
1 => array(
"ID" => 40,
"title" => "Orange"
)
);
$a2 = array(
0 => 31,
1 => 324
);
$defaultValue = 0;
foreach ($a1 as $key => $value) {
$a1[$key]['pages'] = isset($a2[$key]) ? $a2[$key] : $defaultValue;
}
var_dump($a1);
Result:
array(2) {
[0] =>
array(3) {
'ID' =>
int(39)
'title' =>
string(5) "Apple"
'pages' =>
int(31)
}
[1] =>
array(3) {
'ID' =>
int(40)
'title' =>
string(6) "Orange"
'pages' =>
int(324)
}
}
Try this code :-
$newArray = array();
$i=0;
foreach($array1 as $value){
$newArray[$i] = $value;
$newArray[$i][] = $array2[$i];
$i++;
}
Here is code that produce exactly output you are looking for :
<?php
$list1 = array(array('id' => 39,'title' => 'Apple'),array('id' => 40,'title' => 'Orange'));
$list2 = array(array('pages' => 273,'year' => 1981),array('pages' => 386,'year' => 1979));
$newList = array();
$i=0;
foreach($list1 as $firstList){
foreach($list2 as $secondList){
$newList[$i] = array_merge($firstList, $secondList);
}
$i++;
}
echo"<pre>"; print_r($newList); echo"</pre>";
?>
OUTPUT :
Try this
array1[0][pages]=array2[0][pages];
array1[0][year]=array2[0][year];
array1[1][pages]=array2[1][pages];
array1[1][year]=array2[1][year];
for($i=0; $i<count($array1); ++$i){
$array1[$i]['pages'] = $array2[$i];
}
var_dump($array1);
$output = array();
array_walk( $array1, function( $v, $k ) use ( $array2, &$output ) {
$output[] = array_merge( $v, $array2[$k] );
});
If the sizes of the 2 arrays are same you could do something like this
$arr1 = array(
array(
'ID' => 39,
'title' => 'Apple'
),
array(
'ID' => 40,
'title' => 'Orange'
)
);
$arr2 = array(
273,
386
);
$merged = array();
for ($i = 0; $i < count($arr1); $i++) {
$merged[] = array_merge($arr1[$i], array('pages' => $arr2[$i]));
}
var_dump($merged);
or if you don't want a new array
for ($i = 0; $i < count($arr1); $i++) {
$arr1[$i]['pages'] = $arr2[$i];
}
I need to fetch Title summary cover values from this code. Please help me out in fetching the values of rawdata and I need to loop them.
Can someone pls help me out
Array
(
[rawData] => Array
(
[csrf_hash_name] => 57b9481862e81cf2ebe9ed4e962355db
[title] => gfgf
[summary] => hfdhfhfdhdf
[cover] => clockface - 2.png
[id] => Array
(
[0] =>
[1] =>
)
)
just call it by its key:
$arr = Array
(
'rawData' => Array
(
'csrf_hash_name' => 57b9481862e81cf2ebe9ed4e962355db,
'title' => gfgf,
'summary' => hfdhfhfdhdf,
'cover' => clockface - 2.png,
'id' => Array
(
0 => '',
1 => ''
)
);
and then use
$title = $arr['rawData']['title'];
$summary = $arr['rawData']['summary'];
Try this code below
<?php
$array = array(
"rawData" => array(
"csrf_hash_name" => "57b9481862e81cf2ebe9ed4e962355db",
"title" => "gfgf",
"summary" => "hfdhfhfdhdf",
"cover" => "clockface - 2.png",
"id" => array(
0 => "",
1 => ""
)
)
);
foreach($array["rawData"] as $key => $arr) {
$fetchValue = array('title', 'summary', 'cover');
if(in_array($key, $fetchValue)) {
$$key = $arr;
}
}
echo $title;
echo $summary;
echo $cover;
?>
Cheers!
<?php
$array = array(
"rawData" => array(
"csrf_hash_name" => "57b9481862e81cf2ebe9ed4e962355db",
"title" => "gfgf",
"summary" => "hfdhfhfdhdf",
"cover" => "clockface - 2.png",
"id" => array(
0 => "",
1 => ""
)
)
);
$arr2 = array();
foreach($array["rawData"] as $key => $arr) {
$fetchValue = array('title', 'summary', 'cover');
if (in_array($key, $fetchValue)) {
$arr2[$key] = $arr;
}
}
extract($arr2);
echo $title;
echo '<br/>';
echo $summary;
echo '<br/>';
echo $cover;
?>
I am having some difficulty manipulating the below array. I have tried various things and I feel like there should be a simple way to achieve this, but I cannot seem to figure it out. Any tips or help greatly appreciated, thanks!
Array
(
[0] => Array
(
[0] => Array
(
[Color] => Blue
)
[1] => Array
(
[Size] => S
)
)
[1] => Array
(
[0] => Array
(
[Color] => Blue
)
[1] => Array
(
[Size] => M
)
)
)
My desired outcome is:
Array
(
[0] => Array
(
[Color] => Blue
[Size] => S
)
[1] => Array
(
[Color] => Blue
[Size] => M
)
)
This works:
$items = array(
array(
array("Color" => "Blue"),
array("Size" => "S")
),
array(
array("Color" => "Blue"),
array("Size" => "M")
)
);
$new_items = array();
foreach ($items as $item) {
$collect = array();
foreach ($item as $values) {
foreach ($values as $key => $value) {
$collect[$key] = $value;
}
}
$new_items[] = $collect;
}
var_dump($new_items);
Your array is 3 deep, so you need at least 3 nested loops.
Output:
array(2) {
[0]=>
array(2) {
["Color"]=>
string(4) "Blue"
["Size"]=>
string(1) "S"
}
[1]=>
array(2) {
["Color"]=>
string(4) "Blue"
["Size"]=>
string(1) "M"
}
}
2 loops are enough with array_merge
$a = array(
array(
array(
'Color' => 'Blue'
),
array(
'Size' => 'S'
),
),
array(
array(
'Color' => 'Blue'
),
array(
'Size' => 'M'
),
),
);
$c = array();
foreach($a as $b)
{
$ca = array();
if(is_array($b))
{
foreach($b as $array)
{
$ca = array_merge($ca, $array);
}
$c[] = $ca;
}
}
echo '<pre>'.print_r($c,true);
You can use array_map for this:
<?php
function combine($elementArray)
{
return array($elementArray[0]["Color"], $elementArray[1]['Size']);
}
$originalArray = array(
0 => array(
0 => array("Color" => "Blue"),
1 => array("Size" => "S")
),
1 => array(
0 => array( "Color" => "Blue"),
1 => array("Size" => "M")
)
);
$combinedArray = array_map("combine", $originalArray);
echo "<pre>";
print_r($combinedArray);
?>
Also you can use anonymous functions and do it like a pro ;)
$combinedArray = array_map(
function($element){
return array(
"Color" => $element[0]["Color"],
"Size" => $element[1]['Size']
);
},$originalArray);
Or you can even use array_reduce example:
$reducedArray = array_reduce($originalArray, function($result, $item){
$result[] = array(
'Color' => $item[0]['Color'],
'Size' => $item[1]['Size']
);
return $result;
});
Hope this will help
$array =
array(
array(
array(
'color'=>'Blue'
),
array(
'size'=>'s'
)
),
array(
array(
'color'=>'Red'
),
array(
'size'=>'m'
)
)
);
$mA = array();
foreach($array as $k=>$a){
array_push($mA,array_merge($a[0],$a[1]));
}
var_dump($mA);