Merge all child values back into the parent multidimensional array php - php

I have a multidimensional array and i need to merge all the child values back into its parent.
Say i have an array like this:
array(2) {
[XY] =>
array(3) {
[A]=> 20
[B]=> 30
[2]=>
array(2) {
[0]=> 1
[1]=> 2
}
}
[YZ] =>
array(3) {
[A]=> 60
[B]=> 50
[2]=>
array(2) {
[0]=> 3
[1]=> 4
}
}
}
and i want an output like this:
array(2) {
[XY] =>
array(4) {
[A]=> 20
[B]=> 30
[2]=> 1
[3]=> 2
}
[YZ] =>
array(4) {
[A]=> 60
[B]=> 50
[2]=> 3
[3]=> 4
}
}
How can I do this?

here is your solution its work recursive and give any child to meta parent (lvl 1 parent) note:end level Childs give to lvl 1 parent
function giveChildToParentLevel($array)
{
$countOfArray = count($array);
foreach($array as $key=>$value)
{
if(is_array($value))
{
$childitems = giveChildToParentLevel($value);
if(count($childitems) > 0 )
{
unset($array[$key]);
$i = 0;
foreach($childitems as $child)
{
if($i == 0)
$array[$key] = $child;
else
$array[$key.$i] = $child;
$i++;
}
}
}
}
return $array;
}
$array = //your array;
foreach($array as $key=>$value)
{
$array[$key] = giveChildToParentLevel($value);
}
print_r($array);

This code will merge the entire child array into its main parent array, similarly you can do for your requirements.
foreach($allDataInarray as $key => $data) {
$array_keys = array_keys($data);
foreach($array_keys as $key_value) {
if(is_array($data[$key_value])) {
foreach($data[$key_value] as $sub_key => $sub_data) {
$allDataInarray[$key][$sub_key] = $sub_data;
}
unset($allDataInarray[$key][$key_value]);
}
}
}
Note: this is for 2D array.

Related

Sum values of array by key in PHP

I need to find array values by key and sum this values if key exists in other array. I tried to different combination but I havent a good idea.
array(2) {
["www.test.pl"]=>
array(3) {
["category"]=>
array(3) {
}
["category2"]=>
array(3) {
}
}
["www.test2.pl"]=>
array(3) {
["category"]=>
array(3) {
}
["category2"]=>
array(3) {
}
["category3"]=>
array(3) {
}
}
}
I need to compare keys -"category", "category2" Of every URL ... and sum values if I have keys in both array of URLs.
I tries to do this in this example
link to compare array code
You can summ values in ne array:
// $arr1 - starting array
$arr2 = [];
foreach ($arr1 as $arr){
foreach ($arr as $arKey => $arVal) {
if (isset($arr2[$arKey])) {
$arr2[$arKey]['clicks'] += $arVal['clicks'];
$arr2[$arKey]['impressions'] += $arVal['impressions'];
$arr2[$arKey]['ctr'] += $arVal['ctr'];
} else {
$arr2[] = [
'clicks' => $arVal['clicks'],
'impressions' => $arVal['impressions'],
'ctr' => $arVal['ctr'],
];
}
}
}
I hope it is what you want to do
Like this:
foreach($array as $key => $value){
if(isset($array2[$key])){
$sum = $array2[$key]+$value;
}
}

php How to concatenate 2 arrays in one array [duplicate]

This question already has answers here:
How to get all combinations from multiple arrays?
(2 answers)
Closed 5 months ago.
I have the following array with 2 elements:
$attribute_metric = array(2)
{
[0]=>
array(2) {
[0]=>
string(5) "white"
[1]=>
string(6) " Black"
}
[1]=>
array(3) {
[0]=>
string(1) "S"
[1]=>
string(2) " L"
[2]=>
string(2) " M"
}
}
and I want to concatenate its elements in a way where I get one array that has 6 elements
array(6) {
[0]=>
string(8) "white, S"
[1]=>
string(8) "white, L"
[2]=>
string(8) "white, M"
[3]=>
string(8) "Black, S"
[4]=>
string(8) "Black, L"
[5]=>
string(8) "Black, M"
}
I have tried the following but it's not working:
$size = 1;
foreach ($attribute_metric as $key => $value) {
$size = $size * sizeof($value);
}
foreach ($attribute_metric as $key => $value) {
if($key > 0){
foreach ($attribute_metric[0] as $subkey => $subvalue) {
array_push($subvalue,$value);
}
}
}
$array1= $attribute_metric[0]; //['white','black']
$array2= $attribute_metric[1]; // ['S', 'L', 'M']
$resultArray = [];
foreach ($array1 as $color){
foreach ($array2 as $size){
$resultArray[] = $color . ', ' . $size;
}
}
print_r($resultArray);
results
Array
(
[0] => white, S
[1] => white, L
[2] => white, M
[3] => black, S
[4] => black, L
[5] => black, M
)
If the original arrays are not too large then using nested loops would allow you to generate the desired output.
$colours=array('white','black');
$sizes=array('s','m','l');
$out=array();
foreach( $colours as $colour ){
foreach( $sizes as $size ){
$out[]=$colour.', '.$size;
}
}
print_r( $out );
Try this
<?php
$list = array(array('white','Black'), array('S','L','M'));
$result = array();
foreach ($list[0] as $k) {
foreach ($list[1] as $t) {
$result[] = $k.','.$t;
}
}
var_dump($result);
?>
Just for completeness sake and if you want to do it just using array functions:
$output = array_reduce(array_map(function($a) use($attribute_metric) {
return array_map(function($b) use($a) { return $a . ', ' . $b; }, $attribute_metric[1]);
}, $attribute_metric[0]), 'array_merge', []);

array search multidimensional in php?

I want to create a function that for a random array will search for a given key and will return all values for that key in an array. Here is what I have written so far...
$testArray = array (
'subArray1' => array(
'key1' => "Sub array 1 value 1",
'key2' => "Sub array 1 value 2",
'key3' => array(
'subkey1' => array(
'subsubkey' => 'sub sub sub value',
),
),
),
'subArray2' => array(
'key1' => "Sub array 2 value 1",
'key2' => "Sub array 2 value 2",
'key3' => array(
'subkey1' => array(
'subsubkey' => 'sub sub sub value 2',
),
),
),
);
function recursiveSearch($testArray,$key,$results)
{
// var_dump($testArray);
if(is_array($testArray)){
foreach($testArray as $k => $v){
if($k == $key){
return $v;
}
else if(is_array($v)){
array_push($results, recursiveSearch($v,$key,$results));
}
}
}
else{
return ;
}
return $results;
}
$empt = array();
$output = recursiveSearch($testArray,'subsubkey',$empt);
var_dump($output);
This the output I get at the moment... I want to get a simple array with the values in it.
array(2) {
[0]=>
array(1) {
[0]=>
array(1) {
[0]=>
string(17) "sub sub sub value"
}
}
[1]=>
array(2) {
[0]=>
array(1) {
[0]=>
array(1) {
[0]=>
string(17) "sub sub sub value"
}
}
[1]=>
array(2) {
[0]=>
array(1) {
[0]=>
array(1) {
[0]=>
string(17) "sub sub sub value"
}
}
[1]=>
string(19) "sub sub sub value 2"
}
}
}
I am not really sure why the result array is like this ...
The format for the result array that I want is :
['sub sub sub value','sub sub sub value 2']
An improved version of xPheRe
/**
* Recursive find in the given $array and $needle.
* #param $array The input array.
* #param $needle The needle to find.
* #return Returns all the values find by the given key.
*/
function recursiveFind(array $array, $needle)
{
$iterator = new RecursiveArrayIterator($array);
$recursive = new RecursiveIteratorIterator($iterator,
RecursiveIteratorIterator::SELF_FIRST);
$results = array();
foreach ($recursive as $key => $value) {
if ($key === $needle) {
array_push($results, $value);
}
}
return $results;
}
Usage
$output = recursiveFind($testArray, 'subsubkey');
var_dump($output);
Output
array(2) {
[0]=>
string(17) "sub sub sub value"
[1]=>
string(19) "sub sub sub value 2"
}
The updated function of my version is as follows:
function recursiveSearch($testArray,$key){
$empt = array();
function recurSearch($testArray,$key,$results)
{
if(is_array($testArray)){
foreach($testArray as $k => $v){
if($k === $key){
array_push($results,$v);
}
else if(is_array($v)){
$temp = array();
$tempres = recurSearch($v,$key,$temp);
$results = array_merge($results,$tempres);
}
}
}
return $results;
}
$res = recurSearch($testArray,$key,$empt);
return $res;
}
seems to work : )

Create array with keys coming from multiple arrays

I have an array that looks like this:
array(5) {
[0]=>
array(2) {
["id"]=>
string(2) "23"
["my_value"]=>
NULL
}
[1]=>
array(2) {
["id"]=>
string(2) "62"
["my_value"]=>
NULL
}
...
I would like to have an array that as keys have the value of the key "id" in each array and as value have the value of "my_value". However if "my_value" is NULL I want to set a value of 100.
So, the result array would be like this:
array(5) {
[23] => 100
[62] => 100
...
How can I do that cleanly? I have been iterating over with a foreach but I believe it can be done cleaner...
You can use array_map() for populate my_value
$newData = array_map(function($row) {
if ( $row['my_value'] === null ) $row['my_value'] = 100;
return $row;
}, $data);
But you already need a foreach loop because of formatting. So try this:
$newData = array();
foreach ($data as $row) {
$newData[$row['id']] = ($row['my_value'] === null) ? 100 : $row['my_value'];
}
You could do like this:
$arrayUsers = array();//declare array
$arrUser = array("id"=>"23","myvalue"=>NULL); //User 23
$arrayUsers[$arrUser["id"]] = $arrUser; //add
$arrUser = array("id"=>"62","myvalue"=>NULL); //User 62
$arrayUsers[$arrUser["id"]] = $arrUser; //add
var_dump($arrayUsers);
the result is this:
array(2)
{
[23]=> array(2)
{
["id"]=> string(2) "23"
["myvalue"]=> NULL
}
[62]=> array(2)
{
["id"]=> string(2) "62"
["myvalue"]=> NULL
}
}
[EDIT]
$valueArray = array();
foreach($arrayUsers as $id=>$value)
{
$val = ($value["myvalue"]===NULL?100:$value["myvalue"]);
$valueArray[$id] = $val;
}
var_dump($valueArray);
This should behave like you want
$arr = array(5 => array('id'=>23, 'myvalue'=>null),
1 => array('id'=>62, 'myvalue'=>null));
$callback = function($v) {
$id = $v['id'];
$myv = !is_null($v['myvalue']) ? $v['myvalue'] : 100;
return array($id=>$myv);
}
$newarr = array_map($callback, $arr);
you should do it:
foreach($old_array as $value)
$new_array[$value['id']]= ($value['my_value']!==NULL) ? $value['my_value'] : 100 ;
the result will be
array(5) {
[23] => 100
[62] => 100
...
running code example at Codepad.org

PHP Reconstruct Array

I need to reconstruct an array. Here is the original array:
array(8) {
[0] => array(1)
{
["L_TRANSACTIONID0"] => string(17) "62M97388AY676841D"
}
[1] => array(1)
{
["L_TRANSACTIONID1"] => string(17) "9FF44950UY3240528"
}
[2] => array(1)
{
["L_STATUS0"] => string(9) "Completed"
}
[3] => array(1)
{
["L_STATUS1"] => string(9) "Completed"
}
}
I would like to reconstruct it to be as such:
array(2) {
[0] => array(2)
{
["L_TRANSACTIONID0"] => string(17) "62M97388AY676841D"
["L_STATUS0"] => string(9) "Completed"
}
[1] => array(1)
{
["L_TRANSACTIONID1"] => string(17) "9FF44950UY3240528"
["L_STATUS1"] => string(9) "Completed"
}
}
Notice that the KEYS both match with the numeric representation... Is this at all possible?
edit:
here is my code I am using:
foreach($comparison as $key => $val) {
$findme1 = 'L_TRANSACTID'.$i++;
$findme2 = 'L_STATUS'.$c++;
$arrDisable = array($findme1,$findme2);
if( in_array($key, $arrDisable ) ) {
unset( $comparison[ $key ][$val]);
}
if( in_array($key, $arrDisable) ) {
unset( $comparison[ $key ][$val]);
}
}
Try this
$labels = array('L_TRANSACTIONID', 'L_STATUS');
$res = array();
foreach($arr as $val) {
$key = str_replace($labels, '', key($val));
$res[$key] = isset($res[$key]) ? array_merge($res[$key], $val) : $val;
}
print_r($res);
http://codepad.org/MwqTPqtA
If you are certain the the vector cointains pairs L_TRANSACTIONIDn / L_STATUSn keys,that is to say, for each transactionID, there is a corresponding status, what you can do, is to get the number of id/status records (which should equal the length of the initial array, divided by two), and compose the resultin keys, by increasing the current element count.
Could look something like this:
$numItems = sizeof($myInitialArray) / 2;
$newArray = array();
for($i = 0; $i < $numItems; $i++)
{
$itemID = $i * 2; // since we're getting id/status pairs, we're using a step equal to 2
$newArray[] = array(
("L_TRANSACTIONID" . $i) => $myInitialArray[$itemID], // this is the id value
("L_STATUS" . $i) => $myInitialArray[$itemID + 1] // this is the status for that id
);
}
Hope this helps. Have a great day!

Categories