Need some help iterating over this two arrays - php

I have this two arrays:
$arr1['product_detail'] = array(
"26" => array("Blue", "Green"),
"28" => array("S")
);
$arr2['variation'] = array(
"pupc" => array("123456", "654321"),
"pprice" => array(1, 2),
"pqty" => array(10, 11)
);
I need to build a new array containing values based on position, less said:
$arr3 = array(
array("Blue", "S", "123456", 1, 10),
array("Green", "S", "654321", 2, 11)
);
If you notice I mix all the position of both original arrays. I think in something like:
foreach ($arr2 as $key => $value) {
foreach ($value as $key1 => $value1) {
foreach ($value1 as $key2 => $value2) {
foreach ($arr1 as $key3 => $value3) {
echo $key3;
}
}
}
}
But it's very ugly and I think is better ways to do this, any help?

It is good idea to use a function
function array_addition($main_array, $new_array) {
foreach ($new_array as $aItem) {
for ($i=0;$i<=1;$i++) {
$main_array[$i][] = current($aItem) ? current($aItem) : reset($aItem);
next($aItem);
}
}
return $main_array;
}
$arr3 = array();
$arr3 = array_addition($arr3, $arr1['product_detail']);
$arr3 = array_addition($arr3, $arr2['variation']);

$arr1['product_detail'] = array(
"26" => array("Blue", "Green"),
"28" => array("S")
);
$arr2['variation'] = array(
"pupc" => array("123456", "654321"),
"pprice" => array(1, 2),
"pqty" => array(10, 11)
);
function convert_array_index_name_to_number($arr)
{
$temp_ar = array();
foreach($arr as $key=>$val)
{
if(is_array($val))
{
$val = convert_array_index_name_to_number($val);
}
$temp_ar[] = $val;
}
return $temp_ar;
}
$arr1 = convert_array_index_name_to_number($arr1);
$arr2 = convert_array_index_name_to_number($arr2);
$arr3 = array();
for($i=0; $i<$count_of_variations; $i++)
{
$temp_arr = array();
$temp_arr[] = $arr1[0][0][$i];
$temp_arr[] = $arr1[0][1][0];
foreach($arr2[0] as $key => $value)
{
$temp_arr[] = $value[$i];
}
$arr3[] = $temp_arr;
}
Result
Array
(
[0] => Array
(
[0] => Blue
[1] => S
[2] => 123456
[3] => 1
[4] => 10
)
[1] => Array
(
[0] => Green
[1] => S
[2] => 654321
[3] => 2
[4] => 11
)
)

Related

Find differences between two multidimensional arrays in PHP

I have two multidimensional arrays that consist of arrays and objects.
$new = [
'a' => 'b',
'c' => (object)[
'd' => [1 => 11, 2 => 12],
'f' => 'Hello',
],
];
$old = [
'a' => 'b',
'c' => (object) [
'd' => [1 => 11, 2 => 22],
'f' => 'Goodbye',
],
];
I'm trying to find differences between these two arrays by using below function, but the result seems wrong when two objects are compared together. How can I change this function to get correct output?
function compare($array1, $array2)
{
$result = array();
foreach ($array1 as $key => $value) {
if (is_array($value)) {
if (array_key_exists($key, $array2)) {
$recursiveArrayDiff = compare($value, $array2[$key]);
if (count($recursiveArrayDiff)) {
$result[$key] = $recursiveArrayDiff;
}
continue;
}
else {
$result[$key] = $value;
continue;
}
}
if (is_object($value)) {
if (isset($key, $array2) && is_object($array2[$key])) {
$props = array_keys(get_object_vars($value));
foreach ($props as $prop) {
if (isset($array2[$key]->{$prop})) {
if (is_object($value->{$prop}) && is_object($array2[$key]->{$prop})) {
$temp = compare($value->{$prop}, $array2[$key]->{$prop});
if (count($temp)) {
$result[$key] = array($prop => $temp);
}
continue;
} elseif (is_array($value->{$prop}) && is_array($array2[$key]->{$prop})) {
$temp = compare($value->{$prop}, $array2[$key]->{$prop});
if (count($temp)) {
$result[$key] = array($prop => $temp);
}
continue;
} else {
if ($value->{$prop} != $array2[$key]->{$prop}) {
$result[$key] = array($prop => $value->{$prop});
}
}
} else {
$result[$key] = array($prop => $value->{$prop});
}
}
}
}
if ($value != $array2[$key]) {
$result[$key] = $value;
}
}
return $result;
}
The correct and wrong outputs are as follows:
//correct output
Array
(
[c] => stdClass Object
(
[d] => Array
(
[2] => 12
)
[f] => Hello
)
)
//wrong output
Array
(
[c] => stdClass Object
(
[d] => Array
(
[1] => 11
[2] => 12
)
[f] => Hello
)
)

Arrange $_POST to multidimensional array in PHP

I have an form when submitting the form and if print $_POST i will get the output like the following
[type] =>'new',
[class] =>'10',
[div] =>c,
[id_228] => 228,
[title_228]=> First,
[colour_228]=> red,
[id_229] => 229,
[title_229]=> second,
[colour_229]=> blue,
[id_230] => 230,
[title_230]=> third,
[colour_230]=> yellow,
[id_231] => 231,
[title_231]=> fourth,
[colour_231]=> orange,
etc
now i have to store this output to an result array . Please see the result array
result_array[1]=array("Title", 'Color')
so in this result array i have to add $_POST like this
result_array[228]=array("First","red")
result_array[229]=array("Second","blue")
result_array[230]=array("Third","yellow")
result_array[231]=array("Fourth","red")
Please help .
First step should be creating a proper looking array out of this data:
https://3v4l.org/r0HZ9
$post = [
'id_228' => 228,
'title_228' => "First",
'colour_228' => 'red',
'id_229' => 228,
'title_229' => "Second",
'colour_229' => 'blue'];
// Transform data into a proper format
$resultArray = [];
foreach($post as $key => $val) {
$key = explode('_',$key);
$resultArray[$key[1]][$key[0]] = $val;
}
// Now do whatever you want to do
var_dump($resultArray);
Now you could add more logic... If you want the data in your proposed format you could do
$result = [];
foreach($resultArray as $item) {
$result[] = [$item['title'], $item['colour']];
}
https://3v4l.org/WC2B0
EDIT:
Since you added
[type] =>'new',
[class] =>'10',
[div] =>c,
you might want to create a list of allowed fields that should be added, maybe something like:
// Transform data into a proper format
$resultArray = [];
$allowedFields = ['id', 'title', 'colour'];
foreach($post as $key => $val) {
$key = explode('_',$key);
if(in_array($key[0], $allowedFields)) {
$resultArray[$key[1]][$key[0]] = $val;
}
}
https://3v4l.org/NQGfa
You'll have to just loop it and prepare a new array.
$result = array();
foreach ($_POST as $key => $value) {
list($title, $key) = explode('_', $key);
if (!is_array($result[$key])) $result[$key] = array();
$result[$key][$title] = $value;
}
var_dump($result);
Hope this helps.
$arr= ["id_228" => 228, "title_228" => "First",
"colour_228"=> "red",
"id_229" => 229,
"title_229"=> "second",
"colour_229"=> "blue",
"id_230" => 230,
"title_230"=> "third",
"colour_230"=> "yellow",
"id_231" => 231,
"title_231"=> "fourth",
"colour_231"=> "orange" ];
foreach($arr as $key => $value) {
$d = explode( '_', $key );
if(true == is_numeric( $value)) {
continue;
}
$c[$d[1]][]= $value ;
}
print_r($c);
Out put
Array
(
[228] => Array
(
[0] => First
[1] => red
)
[229] => Array
(
[0] => second
[1] => blue
)
[230] => Array
(
[0] => third
[1] => yellow
)
[231] => Array
(
[0] => fourth
[1] => orange
)
)

How to convert multi-dimensional array into single array using PHP?

After implementing database queries, I am getting the multi-dimensional array below.
Two Dimensional Array
Array
(
[0] => Array
(
[t1] => test1
)
[1] => Array
(
[t2] => test2
)
[2] => Array
(
[t3] => test3
)
[3] => Array
(
[t4] => test4
)
[4] => Array
(
[t5] => test5
)
)
but I want to convert it to a single dimensional array, like the format below:
One Dimensional Array
Array (
t1 => test1
t2 => test2
t3 => test3
t4 => test4
t5 => test5
)
How can I do this?
I think you can use array_reduce() function.
For example:
$multi= array(0 => array('t1' => 'test1'),1 => array('t2' => 'test2'),2 => array('t3' => 'test3'),3 => array('t4' => 'test4'));
$single= array_reduce($multi, 'array_merge', array());
print_r($single); //Outputs the reduced aray
You can use as follows :
$newArray = array();
foreach($arrayData as $key => $value) {
foreach($value as $key2 => $value2) {
$newArray[$key2] = $value2;
}
}
Where $arrayData is your DB data array and $newArray will be the result.
Assuming that source array is array of arrays and it has no the same keys:
<?php
$src = [
['t1'=>'test1'],
['t2'=>'test2'],
['t3'=>'test3'],
['t4'=>'test4'],
['t5'=>'test5'],
];
$result = call_user_func_array('array_merge', $src);
result via var_dump():
array(5) {
["t1"]=>
string(5) "test1"
["t2"]=>
string(5) "test2"
["t3"]=>
string(5) "test3"
["t4"]=>
string(5) "test4"
["t5"]=>
string(5) "test5"
}
You can use array_reduce() to change values of array. In callback get key of item using key() and select first item using reset().
$newArr = array_reduce($oldArr, function($carry, $item){
$carry[key($item)] = reset($item);
return $carry;
});
Check result in demo
Try this function,
function custom_function($input_array)
{
$output_array = array();
for ($i = 0; $i < count($input_array); $i++) {
for ($j = 0; $j < count($input_array[$i]); $j++) {
$output_array[key($input_array[$i])] = $input_array[$i][key($input_array[$i])];
}
}
return $output_array;
}
$arr = custom_function($arr);
print_r($arr);
Give it a try, it will work.
You can use this
<?php
$temp = array(array('t1' => 'test1'), array('t2' => 'test2'), array('t3' => 'test3'), array('t4' => 'test4'), array('t5' => 'test5'));
$result_array = array();
foreach ($temp as $val) {
foreach ($val as $key => $inner_val) {
$result_array[$key] = $inner_val;
}
}
print_r($result_array);
?>
// Multidimensional array
$arrdata = Array(
'0' => Array(
't1' => 'test1'
) ,
'1' => Array(
't2' => 'test2'
) ,
'2' => Array(
't3' => 'test3'
)
);
// Convert to a single array
$data = array();
foreach($arrdata as $key => $value) {
foreach($value as $key1 => $value1) {
$data[$key1] = $value1;
}
}
echo $data;
Try array map function.
$singleDimensionArray = array_map('current',$multiDimensionArray);
You can use this if you don't care about keeping the correct array keys
function flattenA(array $array) {
$return = array();
array_walk_recursive($array, function($a) use (&$return) { $return[] = $a; });
return $return;
}
print_r(flattenA($arr));
// Output
Array
(
[0] => test1
[1] => test2
[2] => test3
[3] => test4
[4] => test5
)
Otherwise
function flattenB(array $array) {
$return = array();
array_walk_recursive($array, function($v,$k) use (&$return) { $return[$k] = $v; });
return $return;
}
print_r(flattenB($arr));
// Output
Array
(
[t1] => test1
[t2] => test2
[t3] => test3
[t4] => test4
[t5] => test5
)
Check both on Sandbox
From answer on similar question
For your specific case, I would use array_reduce where I set the initial value with an empty array
array_reduce($arr, function($last, $row) {
return $last + $row;
}, array());
AFTER PHP 7.4
array_reduce($arr, fn ($last, $row) => $last + $row, []);
Result :
[
't1' => 'test1',
't2' => 'test2',
't3' => 'test3',
't4' => 'test4',
't5' => 'test5'
]
Hey #Karan Adhikari Simple like below one:
<?php
$arr1 = array(array("t1" => "test1"), array("t2" => "test2"), array("t3" => "test3"), array("t4" => "test4"), array("t5" => "test5"));
echo "<pre>";
print_r($arr1);//before
$arr2 = array();
foreach($arr1 as $val){
$arr2 = array_merge($arr2, $val);
}
echo "<pre>";
print_r($arr2); // after you get your answer
Please try this function:
function array_merging($multi_array) {
if (is_array($multi_array)) {
$new_arr = array();
foreach ($multi_array as $key => $value) {
if (is_array($value)) {
$new_arr = array_merge($new_arr, array_merging($value));
}
else {
$new_arr[$key] = $value;
}
}
return $new_arr;
}
else {
return false;
}
}
Use this function:
$your_multi_arr = array(array(array('t1'=>'test1'),array('t2'=>'test2'),array('t3'=>'test3'),array('t4'=>'test4')));
$arr1 = array_merging($your_multi_arr);
echo "<pre>";
print_r($arr1);
Hope, this may be useful for you.
You can try traversing the array using PHP while list and each. I took sample code from PHP website the second example you can check it here
$arr = [['t1' => 'test1'],['t2' => 'test2'],['t3' => 'test3'],['t4' => 'test4'],['t5' => 'test5']];
$output = [];
while (list($key, $val) = each($arr)) {
while (list($k, $v) = each($val)) {
$output[$k] = $v;
}
}
print_r($output);
Output created is
Array
(
[t1] => test1
[t2] => test2
[t3] => test3
[t4] => test4
[t5] => test5
)
You can test it on your own in this Sandbox example.
This will do the trick
$array = array_column($array, 't1');
Note: This function array_column introduced in PHP 5.5 so it won't work in earlier versions.
traverse the array and save the key value, Live Demo here.
<?php
$array = array(array('t1' => 'test1'), array('t2' => 'test2'), array('t3' => 'test3'), array('t4' => 'test4'), array('t5' => 'test5'));
$result = [];
array_walk($array, function($value) use(&$result){
foreach($value as $k => $v)
{
$result[$k] = $v;
}
});
var_dump($result);
`$result = "Query"; $key_value = array();`
foreach ($result as $key => $value) {
$key_value[$key['']] = $value[''];
}
//for checking //echo "<pre>" ; print_r($key_value) ; exit;
return $key_value;
pls fill $key['name given in sql query for field'] and $value['name given in sql query for field'] (both are same)
this works for me
$result = [];
foreach($excelEmails as $arr)
{
foreach ($arr as $item){
$result = array_merge($result , $item);
}
}
dd($result);
i would recomment my way to convert all double-dimensional array to single-dimensional array.
<?php
$single_Array = array();
//example array
$array = array(
array('t1' => 'test1'),
array('t2' => 'test2'),
array('t3' => 'test3'),
array('t4' => 'test4'),
array('t5' => 'test5'));
$size = sizeof($array);
//loop to fill the new single-dimensional array
for($count = 0; $count<sizeof($array);$count++)
{
//take the key of multi-dim array
$second_cell = key($array[$count]);
//set the value into the new array
$single_array[$count] = $array[$count][$second_cell];
}
//see the results
var_dump($single_array);
?>
with this script we can take keys and values to create new single-dimensional array.I hope that i was helpfull to you.
you can see the example here: Array Convert Demo

Group pairs in array

I'm trying to group airlines with relations into single chains.
Array
(
[0] => Array
(
[0] => Aeroflot
[1] => S7
[2] => Transaero
)
[1] => Array
(
[0] => Alitalia
[1] => Lufthansa
)
[2] => Array
(
[0] => Transaero
[1] => United
)
[3] => Array
(
[0] => United
[1] => Alitalia
)
[4] => Array
(
[0] => Volotea
[1] => Iberia
)
[5] => Array
(
[0] => Transaero
[1] => Aeroflot
)
)
From that array I need to find connections between elements and combine it to groups. Expected results:
Array
(
[0] => Array
(
[0] => Aeroflot
[1] => S7
[2] => Transaero
[3] => United
[4] => Alitalia
[5] => Lufthansa
)
[1] => Array
(
[0] => Volotea
[1] => Iberia
)
)
Can anyone help with that? I've tried a dozen of ways but still get no success.
The most closest way I've tried which works but not in all cases:
function array_searchRecursive($needle,$haystack) {
foreach($haystack as $key=>$value) {
$current_key=$key;
if($needle===$value OR (is_array($value) && array_searchRecursive($needle,$value) !== false)) {
return $current_key;
}
}
return false;
}
foreach ($newarr as $key => $airlines)
{
foreach ($airlines as $lastkey => $airline)
{
$index = array_searchRecursive($airline,$newarr);
echo $airline.$index."\n";
if ($index !== false)
{
$newarr[$index] = array_merge($newarr[$index],$airlines);
$lastarr[] = $index;
}
}
}
But it doesn't match all values in array.
Recursive function will help you. You are welcome )
$arr = array(
array('Aeroflot','S7','Transaero'),
array('Alitalia','Lufthansa'),
array('Transaero','United'),
array('United','Alitalia'),
array('Volotea','Iberia'),
array('Transaero','Aeroflot')
);
function getConnections($arr,$curr_line_n=0,$num=0) {
for($i=0;$i<count($arr[$curr_line_n]);$i++) {
$cur_air_name = $arr[$curr_line_n][$i];
for($k=$curr_line_n+1; $k<count($arr); $k++) {
for($l=0;$l<count($arr[$k]);$l++) {
if ($arr[$k][$l]==$cur_air_name) {
$arr[$curr_line_n] = array_values(array_unique(array_merge($arr[$curr_line_n],$arr[$k])));
array_splice($arr,$k,1);
$num++;
$arr = getConnections($arr,$curr_line_n,$num);
}
}
}
}
$num++;
$curr_line_n++;
if ($curr_line_n!=count($arr)) {
$arr = getConnections($arr,$curr_line_n,$num);
}
return $arr;
}
print_r(getConnections($arr));
As per your example you are just grouping sub arrays by taking first sub array as reference. for example if you have any elements common in first sub array and in subsequent sub arrays then you combine them into one sub array.
<?php
$arr = array(
array('a', 'b', 'c', 'd'),
array('d', 't'),
array('t', 'f'),
array('k', 'o'),
array('p', 'z')
);
$arr_implode = array();
foreach ($arr as $key => $value) {
if (is_array($value)) {
$arr_implode[$key] = implode('', $value);
} else {
$arr_implode[$key] = $value;
}
}
$arr_key = array();
$result = array();
$count = count($arr_implode);
$tempj = 0;
for ($i = 0; $i <= $count; $i++) {
$flag = FALSE;
for ($j = ($i + 1); $j < $count; $j++) {
similar_text($arr_implode[$i], $arr_implode[$j], $percent);
if ($percent > 0) {
$result[] = array_merge($arr[$i],$arr[$j]);
break;
} else {
$result[] = $arr[$j];
break;
}
}
}
foreach($result as $key => $val){
$result[$key] = array_unique($val);
}
echo "<pre>";
print_r($result);
echo "</pre>";
?>
Try this code.
$arr = [
['Aeroflot', 'S7', 'Transaero'],
['Alitalia', 'Lufthansa'],
['Transaero', 'United'],
['United', 'Alitalia'],
['Volotea', 'Iberia'],
['Transaero', 'Aeroflot']
];
$hash = [];
$result = [];
foreach($arr as $set){
foreach($set as $el){
if(!$hash[$el]) $hash[$el] = [] ;
$hash[$el] = array_merge($hash[$el], $set);
}
}
function merge_connections(&$h, $key){
if(!$h[$key]) return [];
$data = [$key];
$rels = $h[$key];
unset($h[$key]);
foreach($rels as $rel){
if($rel==$key) continue;
$data = array_merge($data, merge_connections($h, $rel));
}
return $data;
}
foreach(array_keys($hash) as $company){
if(!$hash[$company]) continue;
array_push($result, merge_connections($hash, $company));
}
print_r($result);

Merge 2 Arrays and Sum the Values (Numeric Keys)

I have 2 arrays
Array
(
[010156] => Array
(
[supp_number] => 010156
[totalamount] => 4.113,23
[debtorcred] => H
[amount1] => 4.113,23-
[amount2] =>
[amount3] =>
[amount4] =>
[amount5] =>
[amount6] =>
)
)
Array
(
[010156] => Array
(
[supp_number] => 010156
[totalamount] => 4.113,23
[debtorcred] => H
[amount1] => 4.113,23-
[amount2] =>
[amount3] =>
[amount4] =>
[amount5] =>
[amount6] =>
)
)
Is it possible that I can combine these separate arrays into one and add the values together so that the outcome will be:
Array
(
[010156] => Array
(
[supp_number] => <<<TOTAL >>>
[totalamount] => <<<TOTAL >>>
[debtorcred] => <<<TOTAL >>>
[amount1] => <<<TOTAL >>>
[amount2] => <<<TOTAL >>>
[amount3] => <<<TOTAL >>>
[amount4] => <<<TOTAL >>>
[amount5] => <<<TOTAL >>>
[amount6] => <<<TOTAL >>>
)
)
This is the function I have at the moment but I cannot seem to make it work:
function array_merge_numeric_values()
{
$arrays = func_get_args();
$merged = array();
foreach ($arrays as $array)
{
foreach ($array as $key => $value)
{
if ( ! isset($merged[$key]))
{
$merged[$key] = $value;
}
else
{
$merged[$key] += $value;
}
}
}
This actual calculation can be done in 2 lines of code, no need for loops:
http://codepad.viper-7.com/ieSkHQ
$arr1 = array('amount1' => 1, 'amount2' => 6);
$arr2 = array('amount1' => 2, 'amount2' => 7);
$add = function($a, $b) { return $a + $b; };
$summedArray = array_map($add, $arr1, $arr2);
print_r($summedArray);
Youl'll just need to make the appropriate adjustment to account for you nested structure.
Create a new empty array and loop in the first array as following:
$array1 = array('my_num' => 10, 'my_num2' => 20);
$array2 = array('my_num' => 15, 'my_num2' => 25);
$newArray = array();
foreach($array1 as $key => $value){
if(isset($array2[$key])){
$newArray[$key] = $value+$array2[$key];
} else {
$newArray[$key] = $value;
}
}
print_r($newArray);
$value in your case is an array, not a value. You can try this:
function array_merge_numeric_values()
{
$arrays = func_get_args();
$merged = array();
foreach ($arrays as $array)
{
foreach ($array as $key => $value)
{
if(!isset($merged[$key]))
{
$merged[$key] = array();
}
foreach($value as $kk => $vv)
{
if ( ! isset($merged[$key][$kk]))
{
$merged[$key][$kk] = $vv;
}
else
{
$merged[$key][$kk] += $vv;
}
}
}
}
}

Categories