I want to combine two arrays into a dictionary.
The keys will be the distinct values of the first array, the values will be all values from the second array, at matching index positions of the key.
<?php
$a=[2,3,4,5,6,7,8,9,10];
$b=[1,1,3,2,1,2,6,8,8];
?>
array_combine($b,$a);
Expected result as
<?php
/*
Value '1' occurs at index 0, 1 and 4 in $b
Those indices map to values 2, 3 and 6 in $a
*/
$result=[1=>[2,3,6],3=>4,2=>[5,7],6=>8,8=>[9,10]];
?>
There are quite a few PHP array functions. I'm not aware of one that solves your specific problem. you might be able to use some combination of built in php array functions but it might take you a while to weed through your choices and put them together in the correct way. I would just write my own function.
Something like this:
function myCustomArrayFormatter($array1, $array2) {
$result = array();
$num_occurrences = array_count_values($array1);
foreach ($array1 AS $key => $var) {
if ($num_occurrences[$var] > 1) {
$result[$var][] = $array2[$key];
} else {
$result[$var] = $array2[$key];
}
}
return $result;
}
hope that helps.
$a=[2,3,4,5,6,7,8,9,10];
$b=[1,1,3,2,1,2,6,8,8];
$results = array();
for ($x = 0; $x < count($b); $x++) {
$index = $b[$x];
if(array_key_exists ($index, $results)){
$temp = $results[$index];
}else{
$temp = array();
}
$temp[] = $a[$x];
$results[$index] = $temp;
}
print_r($results);
Here's one way to do this:
$res = [];
foreach ($b as $b_index => $b_val) {
if (!empty($res[$b_val])) {
if (is_array($res[$b_val])) {
$res[$b_val][] = $a[$b_index];
} else {
$res[$b_val] = [$res[$b_val], $a[$b_index]];
}
} else {
$res[$b_val] = $a[$b_index];
}
}
var_dump($res);
UPDATE: another way to do this:
$val_to_index = array_combine($a, $b);
$result = [];
foreach ($val_to_index as $value => $index) {
if(empty($result[$index])){
$result[$index] = $value;
} else if(is_array($result[$index])){
$result[$index][] = $value;
} else {
$result[$index] = [$result[$index], $value];
}
}
var_dump($result);
Related
This question already has answers here:
Code after a return statement in a PHP function
(3 answers)
Closed 6 months ago.
please check my code. i have some program to return the third largest word in a given array.
if in the third largest word has a same letters long, so retrun the last one.
for example ['world', 'hello', 'before', 'all', 'dr'] the output should be 'hello'.
my program is working fine, however when I want to echo the $result, the code doesn't execute.
here is my code:
<?php
$array = ['world', 'hello', 'before', 'all', 'dr'];
$array2 = [];
foreach ($array as $value) {
$array2[$value] = strlen($value);
}
asort($array2);
$slice = array_slice($array2, -3);
$array3 = [];
foreach ($slice as $key => $value) {
$array3[] = $key;
}
$result = "THIS RESULT SHOULD BE RE ASSIGNED, BUT WHY !!!!!";
for ($i = count($array3) - 1; $i >= 0; $i--) {
if ($i == 0) {
$result = $array3[$i];
return $result;
}
if (strlen($array3[$i]) == strlen($array3[$i - 1])) {
$result = $array3[$i];
return $result;
}
}
echo "THIS LINE IS NOT WORKING";
echo $result;
You have to use break instead of return.
<?php
$array = ['world', 'hello', 'before', 'all', 'dr'];
$array2 = [];
foreach ($array as $value) {
$array2[$value] = strlen($value);
}
asort($array2);
$slice = array_slice($array2, -3);
$array3 = [];
foreach ($slice as $key => $value) {
$array3[] = $key;
}
$result = "";
for ($i = count($array3) - 1; $i >= 0; $i--) {
if ($i == 0) {
$result = $array3[$i];
break;
}
if (strlen($array3[$i]) == strlen($array3[$i - 1])) {
$result = $array3[$i];
break;
}
}
echo $result;
Simply remove the return statements in the loop. instead of return, perhaps use break.
You can try this way as well.
<?php
/**
* Read more about here
* https://www.php.net/manual/en/function.usort.php
*/
function sort_by_length($a,$b){
return strlen($b)-strlen($a);
}
$array =['world', 'hello', 'before', 'all', 'dr'];
usort($array,'sort_by_length'); // sorting array with a custom function.
if(count($array) >= 2) {
$sliced = array_slice($array, 2);
$result = $sliced[0];
/**
* Read more at
* 1. https://www.php.net/manual/en/function.next.php
* 2. https://www.php.net/manual/en/function.current.php
*/
while(strlen(current($sliced)) == strlen(next($sliced))){
$result = current($sliced);
}
echo $result;
} else {
echo "Not enough items in array.";
}
This will output
hello
Remove the return .It return the value so any code after it will not be executed.
I need to re-arrange a php multidimensional array so that to 'match' corresponding values from different arrays;
this is my reproducible example
<?php
// my original array
$myar= array(
array('A'=>'xxx','B'=>1),
array('A'=>'yyy','B'=>2),
array('A'=>'xxx','B'=>3),
array('A'=>'yyy','B'=>4)
);
print_r($myar);
// my desired result, new array
$myar_new= array(
array('xxx'=>1,'yyy'=>2),
array('xxx'=>3,'yyy'=>4)
);
print_r($myar_new);
?>
any help for that?
thanks
If I got your logic right then this function is what you need.
(Edited)
function strange_reformat($srcArray) {
$newArray = [];
$c = count($srcArray);
$i = 0;
$groupStart = null;
$collect = [];
while($i < $c) {
$row = current($srcArray[$i]);
if ($row == $groupStart) {
$newArray[] = $collect;
$collect = [];
}
$tmp = array_values($srcArray[$i]);
$collect[] = [$tmp[0] => $tmp[1]];
if ($groupStart === null) $groupStart = $row;
$i++;
}
$newArray[] = $collect;
return $newArray;
}
print_r(strange_reformat($myar));
yes, that's it...
but now I need to generalise it, please consider this case
$myar= array(
array('A'=>'xxx','B'=>1),
array('A'=>'yyy','B'=>2),
array('A'=>'zzz','B'=>5),
array('A'=>'xxx','B'=>3),
array('A'=>'yyy','B'=>4),
array('A'=>'zzz','B'=>6)
);
function strange_reformat($srcArray) {
$newArray = [];
$c = count($srcArray);
for ($i=0; $i<$c; $i+=3) {
$first = array_values($srcArray[$i]);
$second = array_values($srcArray[$i+1]);
$third = array_values($srcArray[$i+2]);
$newArray[] = [$first[0]=>$first[1], $second[0]=>$second[1], $third[0]=>$third[1]];
}
return $newArray;
}
print_r(strange_reformat($myar));
I'm facing a technical problem here, I have an array [PER_DAY, PER_SIZE, PER_TYPE], I want to find combination all of the item without repeating the element, the result should be
[PER_DAY]
[PER_SIZE]
[PER_TYPE]
[PER_DAY, PER_SIZE]
[PER_DAY, PER_TYPE]
[PER_SIZE, PER_TYPE]
[PER_DAY, PER_SIZE, PER_TYPE]
This code repeating same value, so the result is too much.
$arr = ['PER_DAY', 'PER_SIZE', 'PER_TYPE'];
$result = [];
function combinations($arr, $level, &$result, $curr=[]) {
for($i = 0; $i < count($arr); $i++) {
$new = array_merge($curr, array($arr[$i]));
if($level == 1) {
sort($new);
if (!in_array($new, $result)) {
$result[] = $new;
}
} else {
combinations($arr, $level - 1, $result, $new);
}
}
}
for ($i = 0; $i<count($arr); $i++) {
combinations($arr, $i+1, $result);
}
This question possible duplicate, but I cannot found example similar like this, thanks.
function pc_array_power_set($array) {
// initialize by adding the empty set
$results = array(array( ));
foreach ($array as $element)
foreach ($results as $combination)
array_push($results, array_merge(array($element), $combination));
return array_filter($results);
}
$set = ['PER_DAY', 'PER_SIZE', 'PER_TYPE'];
$power_set = pc_array_power_set($set);
echo '<pre>';
print_r($power_set);
You have make combination from array, will help you :-PHP array combinations
array one: 1,3,5,7
array two: 2,4,6,8
the array i want would be 1,2,3,4,5,6,7,8
I'm just using numbers as examples. If it was just numbers i could merge and sort but they will be words. So maybe something like
array one: bob,a,awesome
array two: is,really,dude
should read: bob is a really awesome dude
Not really sure how to do this. Does PHP have something like this built in?
You could write yourself a function like this:
function array_merge_alternating($array1, $array2) {
if(count($array1) != count($array2)) {
return false; // Arrays must be the same length
}
$mergedArray = array();
while(count($array1) > 0) {
$mergedArray[] = array_shift($array1);
$mergedArray[] = array_shift($array2);
}
return $mergedArray;
}
This function expects two arrays with equal length and merges their values.
If you don't need your values in alternating order you can use array_merge. array_merge will append the second array to the first and will not do what you ask.
Try this elegant solution
function array_alternate($array1, $array2)
{
$result = Array();
array_map(function($item1, $item2) use (&$result)
{
$result[] = $item1;
$result[] = $item2;
}, $array1, $array2);
return $result;
}
This solution works AND it doesn't matter if both arrays are different sizes/lengths:
function array_merge_alternating($array1, $array2)
{
$mergedArray = array();
while( count($array1) > 0 || count($array2) > 0 )
{
if ( count($array1) > 0 )
$mergedArray[] = array_shift($array1);
if ( count($array2) > 0 )
$mergedArray[] = array_shift($array2);
}
return $mergedArray;
}
Try this function:
function arrayMergeX()
{
$arrays = func_get_args();
$arrayCount = count($arrays);
if ( $arrayCount < 0 )
throw new ErrorException('No arguments passed!');
$resArr = array();
$maxLength = count($arrays[0]);
for ( $i=0; $i<$maxLength; $i+=($arrayCount-1) )
{
for ($j=0; $j<$arrayCount; $j++)
{
$resArr[] = $arrays[$j][$i];
}
}
return $resArr;
}
var_dump( arrayMergeX(array(1,3,5,7), array(2,4,6,8)) );
var_dump( arrayMergeX(array('You', 'very'), array('are', 'intelligent.')) );
var_dump( arrayMergeX() );
It works with variable numbers of arrays!
Live on codepad.org: http://codepad.org/c6ZuldEO
if arrays contains numeric values only, you can use merge and sort the array.
<?php
$a = array(1,3,5,7);
$b = array(2,4,6,8);
$merged_array = array_merge($a,$b);
sort($merged,SORT_ASC);
?>
else use this solution.
<?php
function my_merge($array1,$array2)
{
$newarray = array();
foreach($array1 as $key => $val)
{
$newarray[] = $val;
if(count($array2) > 0)
$newarray[] = array_shift($array2)
}
return $newarray;
}
?>
hope this help
Expects both arrays to have the same length:
$result = array();
foreach ($array1 as $i => $elem) {
array_push($result, $elem, $array2[$i]);
}
echo join(' ', $result);
Hi anybody can help me to find the maximum value of the array that are given in the below . i expect the result of 650 is the maximum value....
$my_array = array(array(128,300,140)10,15,array(130,array(500,650)));
Here you go, using RecursiveArrayIterator in 3 readable lines of code:
$it = new RecursiveIteratorIterator(new RecursiveArrayIterator($array));
$flattenedArray = iterator_to_array($it);
$max = max($flattenedArray);
Or, if you want to not flatten (and copy), but prefer to iterate (uses far less memory, but slower):
$it = new RecursiveIteratorIterator(new RecursiveArrayIterator($array));
$max = 0;
foreach ($it as $value) {
$max = max($value, $max);
}
Flatten the array, then call max() on it. The return value of max() should be 650 from your example.
Also possible is
$data = array(array(128,300,140),10,15,array(130,array(500,650)));
$max = 0;
array_walk_recursive(
$data,
function($val) use (&$max) {
if($val > $max) $max = $val;
}
);
echo $max; // 650
You could also do it recursively, if the item is an array, call the function again to return the max item from that array.
In the end you should have always the max item and then in the last iteration, you could call the max from those results.
This does the trick:
function flatten($ar) {
$toflat = array($ar);
$res = array();
while (($r = array_shift($toflat)) !== NULL) {
foreach ($r as $v) {
if (is_array($v)) {
$toflat[] = $v;
} else {
$res[] = $v;
}
}
}
return $res;
}
$arr = array(array(128,300,140),10,15,array(130,array(500,650)));
echo max(array_flatten($arr));
EDIT: Updated flatten array with the one at How to "flatten" a multi-dimensional array to simple one in PHP?
<?php
$my_array = array(array(128,300,140),10,15,array(130,array(500,650)));
function findLargest($arr) {
$largest = 0;
foreach ($arr as $item) {
if (is_array($item)) {
$item = findLargest($item);
}
if ($item > $largest) {
$largest = $item;
}
}
return $largest;
}
echo "Largest is ".findLargest($my_array)."\n";
?>
function maximum($in)
{
if (!is_array($in)) $max = $in;
else foreach ($in as $element)
{
$elementMax = maximum($element);
if (isset($max)) $max = max($elementMax, $max); else $max = $elementMax;
}
return $max;
}