creating dimensional array with 2 single array - php

i have 2 arrays and i want 2 create 2D array for create mysql record
Array
(
[0] => a
[1] => b
[2] => c
)
Array
(
[0] => 1
[1] => 2
[2] => 3
)
i want 2 merge them into 2 dimensional array like this
Array
(
[0] => Array
(
[designation_id] => 1
[judge_name] => a
)
[1] => Array
(
[designation_id] => 2
[judge_name] => b
)
[2] => Array
(
[designation_id] => 3
[judge_name] => c
)
)
i use array_merge_recursive and it generates result like this
Array
(
[0] => a
[1] => b
[2] => c
[3] => 1
[4] => 2
[5] => 3
)

Assuming there will always be the same amount of values in $array1 as there are in $array2..
$array1 = Array("a","b","c");
$array2 = Array(1,2,3);
$newArray = Array();
foreach($array1 as $key => $arr1Val){
$newArray[$key]['designation_id'] = $array2[$key];
$newArray[$key]['judge_name'] = $array1[$key];
}
Of course, you will have to alter $array1 and $array2 to your needs, but you understand the basic idea. Check it here.

Assuming $array1 is the judge_name and $array2 is the designation_id
$newArray = array();
for($i=0; $i<count($array1); $i++)
{
$newArray[] = array(
'designation_id' => $array2[$i],
'judge_name' => $array1[$i]
);
}
Codepad Demo
Outputs
Array
(
[0] => Array
(
[designation_id] => 1
[judge_name] => a
)
[1] => Array
(
[designation_id] => 2
[judge_name] => b
)
[2] => Array
(
[designation_id] => 3
[judge_name] => c
)
)

simple as hell
$array1 = array('a', 'b', 'c');
$array2 = array(1,2,3);
$merged = array();
foreach($array1 as $key => $value)
{
$merged[$key] = array(
'judge_name' => $value,
'designation_id' => array_key_exists($key, $array2) ? $array2[$key] : null
);
}

Assuming that both arrays are of same size
$length = count($array1);
$finalArray = array();
for ($i = 0; $i < $length; $i++) {
$temp = array();
$temp['designation_id'] = $array1[$i];
$temp['judge_name'] = $array2[$i];
$finalArray[$i] = $temp;
}

$a = array('a', 'b', 'c');
$b = array(1,2,3);
$output = array_map(function($i, $j){
return array(
'judge_name' => $j,
'designation_id' => $i
);
}, $a, $b);
var_dump($output);
Outputs
array(3) {
[0]=>
array(2) {
["judge_name"]=>
int(1)
["designation_id"]=>
string(1) "a"
}
[1]=>
array(2) {
["judge_name"]=>
int(2)
["designation_id"]=>
string(1) "b"
}
[2]=>
array(2) {
["judge_name"]=>
int(3)
["designation_id"]=>
string(1) "c"
}
}

If you have PHP >= 5.3 you could use MultipleIterator for that purpose:
$designations = array(1, 2, 3);
$judges = array('a', 'b', 'c');
$mt = new MultipleIterator(MultipleIterator::MIT_KEYS_ASSOC);
$mt->attachIterator(new ArrayIterator($designations), "designation_id");
$mt->attachIterator(new ArrayIterator($judges), "judge_name");
$final = iterator_to_array($mt, false);
print_r($final);
Demo
It iterates over multiple arrays, taking a value from each array at every iterator; you can assign a key for each array that will be used to form a single array item.
Afterwards you convert the results into an array using iterator_to_array().

$new1=array("a","b","c");
$new2=array("1","2","3");
$req=array();
$d=0;
foreach($new1 as $value1)
{
foreach($new2 as $value2)
{
$req[$d]["designation_id"]=$value1;
$req[$d]["judge_name"]=$value2;
$d++;
}
}
echo "<pre>";
print_r($req);

Related

Sum like values in Multi-Dimensional array php

I need to sum the values in element 1 of my array where the values in element 0 are duplicate.
Here's a small piece of my array
Array
(
[0] => 3
[1] => 1
)
Array
(
[0] => 3
[1] => 2
)
Array
(
[0] => 3
[1] => 128
)
Array
(
[0] => 39
[1] => 4
)
The results i'm expecting to see
Array
(
[0] => 3
[1] => 131
)
Array
(
[0] => 39
[1] => 4
)
I'm still really new to PHP so any help is greatly appreciated.
You can use a combination of array_intersect, array_column and array_sum to only iterate twice. (One for each unique column 0 value).
$col0 = array_column($arr, 0);
$col1 = array_column($arr, 1);
Foreach(array_unique($col0) as $val){
$res[] = [$val, array_sum(array_intersect_key($col1, array_intersect($col0,[$val])))];
}
Var_dump($res);
https://3v4l.org/gKb5b
The way I've done it is made sure all duplicates where put in the same array.
// Your data
$sample = [[3, 1],[3, 2],[3, 128],[39, 4]];
foreach($sample as $array){
$tmp[$array[0]][] = $array[1];
}
# Output: {"3":[1,2,128],"39":[4]}
Now sum the arrays, and put it back to the structure it originally was.
foreach($tmp as $k => $v){
$new[] = [$k, array_sum($v)];
}
# Output: [[3,131],[39,4]]
But many roads lead to Rome.
Try this code. It may help you.
$array = array(["0" => 3, "1" => 1] , ["0" => 3, "1" => 2], ["0" => 3, "1" => 128], ["0" => 39, "1" => 4]);
$finalArray = [];
foreach($array as $a) {
$finalArray[$a[0]][0] = $a[0];
$finalArray[$a[0]][1] = !isset($finalArray[$a[0]][1]) ? $a[1] : $finalArray[$a[0]][1] + $a[1];
}
echo '<pre>';
print_r($finalArray);
exit;
You could do something like this. I have separated into two foreach. Hope it helps.
<?php
$a = [[3,1],[3,2],[3,128],[39,4]];
$result=[];
$temp = [];
foreach($a as $line) {
$temp[$line[0]] += $line[1];
}
foreach($temp as $k => $value) {
$result[]=[$k ,$value];
}
$data =
[
[3,1],
[3,2],
[3,128],
[39,4]
];
foreach($data as $item)
$sums[$item[0]] = ($sums[$item[0]] ?? 0) + $item[1];
$result = array_map(null, array_keys($sums), $sums);
var_export($result);
Output:
array (
0 =>
array (
0 => 3,
1 => 131,
),
1 =>
array (
0 => 39,
1 => 4,
),
)
$arr = [ [ 3, 1],[ 3, 2 ],[ 3, 128], [ 39, 4]];
$sum = [];
foreach($arr as $value) {
$sum[$value[0]][] = $value[1];
}
foreach($sum as $key=>$value ) {
$result[] = [ $key, array_sum($value)];
}
Output:
Array
(
[0] => Array
(
[0] => 3
[1] => 131
)
[1] => Array
(
[0] => 39
[1] => 4
)
)

Merging 3 arrays in PHP

I have 3 arrays as below.
$array1 = Array
(
[0] => 05/01
[1] => 05/02
)
$array2 =Array
(
[0] => ED
[1] => P
)
$array3 =Array
(
[0] => Mon
[1] => Tue
)
I want to merge these 3 arrays as below $result_array. I have written a code as below. But It gave a empty array.
$result_array =Array
(
[0] => Array
(
[0] => 05/01
[1] => ED
[2] => Mon
)
[1] => Array
(
[0] => 05/02
[1] => P
[2] => Tue
)
)
Code:
for($z=0; $z<count($array1); $z++){
$all_array[$z][] = array_merge($array1[$z],$array2[$z] );
$all_array2[$z] = array_merge($all_array[$z],$array3[$z] );
}
Please help me to do this.
Simply foreach over the first array and use the index as the key to the other arrays.
foreach ( $array1 as $idx => $val ) {
$all_array[] = [ $val, $array2[$idx], $array3[$idx] ];
}
Remember this will only work if all 3 arrays are the same length, you might like to check that first
You can simply walk through the first array with a foreach loop then access the corresponding arrays and combine the results into one big array. This will only work if the arrays are the same length so it's worth checking that before to stop any errors. Something like this:
<?php
$arr1 = ['05/01', '05/02'];
$arr2 = ['ED', 'P'];
$arr3 = ['Mon', 'Tue'];
$combined = [];
if (count($arr1) != count($arr2) || count($arr1) != count($arr3))
die("Array lengths do not match!");
foreach ($arr1 as $key => $val) {
$combined[] = [$val, $arr2[$key], $arr3[$key]];
}
var_dump($combined);
You can see an eval.in of this working here - https://eval.in/833893
Create an sample array and push to each array value with respective key
$sample = array();
for($z=0; $z<count($array1); $z++){
$sample[]=array($array1[$z],$array2[$z],$array3[$z]);
}
print_r($sample);
Out put is
Array ( [0] => Array (
[0] => 05/01
[1] => ED
[2] => Mon
)
[1] => Array (
[0] => 05/02
[1] => P
[2] => Tue
)
)
this work for n of arrays and dynamic length of array
function mergeArrays(...$arrays)
{
$length = count($arrays[0]);
$result = [];
for ($i=0;$i<$length;$i++)
{
$temp = [];
foreach ($arrays as $array)
$temp[] = $array[$i];
$result[] = $temp;
}
return $result;
}
$x = mergeArrays(['05/01' , '05/02'] , ['ED' , 'P'] , ['Mon' , 'Tus']);
$y = mergeArrays(['05/01' , '05/02' , 'X'] , ['ED' , 'P' , 'Y'] , ['Mon' , 'Tus' , 'Z'] , ['A' , 'B' , 'C']);
var_dump($x);
var_dump($y);
function merge($file_name, $titles, $description)
{
$result = array();
foreach($file_name as $key=>$name )
{
$result[] = array( 'file_name' => $name, 'title' => $titles[$key],
'description' => $description[ $key ] );
}
return $result;
}
$array1 = Array
(
'05/01',
'05/02'
);
$array2 = Array
(
'ED',
'P'
);
$array3 =Array
(
'Mon',
'Tue'
);
$result_array = array();
foreach ($array1 as $key=>$val)
{
$result_array[$key] = array($array1[$key],$array2[$key],$array3[$key]);
}
echo "<PRE>"; print_r($result_array);

Select and delete random keys from multidimensional array

I have one problem with randomness.
I have example array.
$example=array(
'F1' => array('test','test1','test2','test5'),
'F2' => array('test3', 'test4'),
'F3' => array('one','twoo','threee','x'),
'F5' => array('wow')
)
I want to choose random keys from array to other array with specified size. In this second array I want values from other groups.
For example i got
$amounts = array(4,3,1,2,1);
I want to choose randomly specified ammount of variables ($amount) from $example, but of course - always from other groups.
Example result:
$result=(
array(4) => ('test','test4','x','wow'),
array(3) => ('test2','test3','three'),
array(1) => ('test1')
array(2) => ('test5','one')
array(1) => ('twoo')
What I tried so far?
foreach($amounts as $key=>$amount){
$random_key[$key]=array_rand($example,$amount);
foreach($result[$key] as $key2=>$end){
$todelete=array_rand($example[$end]);
$result[$key][$key2]=$example[$amount][$todelete]
}
}
I don't know now, what to fix or to do next.
Thanks for help!
$example = array(
'F1' => array('test', 'test1', 'test2', 'test5'),
'F2' => array('test3', 'test4'),
'F3' => array('one', 'twoo', 'threee', 'x'),
'F5' => array('wow')
);
$amounts = array(4, 3, 1, 2, 1);
$result = array();
$example = array_values($example);
//randomize the array
shuffle($example);
foreach ($example as $group) {
shuffle($group);
}
//sort the example array by child length
usort($example, function ($a, $b) {
return count($b) - count($a);
});
foreach ($amounts as $amount) {
$tmpResult = array();
for ($i = 0; $i < $amount; $i++) {
if(empty($example[$i])){
throw new \InvalidArgumentException('The total number of values in the array exceed the amount inputed');
}
$tmpResult[] = array_pop($example[$i]);
}
$result[] = $tmpResult;
//sort the example array again by child length
usort($example, function ($a, $b) {
return count($b) - count($a);
});
}
print_r($result);
test result:
Array
(
[0] => Array
(
[0] => test5
[1] => x
[2] => test4
[3] => wow
)
[1] => Array
(
[0] => test2
[1] => threee
[2] => test3
)
[2] => Array
(
[0] => test1
)
[3] => Array
(
[0] => twoo
[1] => test
)
[4] => Array
(
[0] => one
)
)

Split array into chunks of alternating sizes

I have an array:
Array
(
[0] => 0
[1] => 1
[2] => 2
[3] => 3
[4] => 4
[5] => 5
[6] => 6
[7] => 7
[8] => 8
[9] => 9
)
I want to split the array into alternating chunks. (size 2 then 3 then 2 then 3 etc)
Array
(
[0] => Array
(
[0] => 0
[1] => 1
[2] => 2
)
[1] => Array
(
[0] => 3
[1] => 4
)
[2] => Array
(
[0] => 5
[1] => 6
[2] => 7
)
[3] => Array
(
[0] => 8
[1] => 9
)
)
That should work:
$a = array(0 => 0,1 => 1,2 => 2,3 => 3,4 => 4, 5 => 5, 6 => 6,7 => 7,8 => 8,9 => 9);
$chunks = array();
$i=1;
while(count($a)){
$chunks[] = array_splice($a, 0,(2+($i%2)),array());
$i++;
}
echo "<pre>";
var_dump($chunks);
You can use array_splice for splitting the array, but you need to set conditions right? On what basis do you wanna split them?
And you can use array_merge to bring them back into an array of arrays.
In case of your current code, the code will be:
PHP Code
<?php
$array = array(0,1,2,3,4,5,6,7,8,9);
$final = array(
array_splice($array, 0, 3),
array_splice($array, 1, 2),
array_splice($array, 1, 2),
array_splice($array, 1, 2),
);
print_r($final);
?>
Output
Array
(
[0] => Array
(
[0] => 0
[1] => 1
[2] => 2
)
[1] => Array
(
[0] => 4
[1] => 5
)
[2] => Array
(
[0] => 6
[1] => 7
)
[3] => Array
(
[0] => 8
[1] => 9
)
)
Fiddle here: http://codepad.org/JzxcZ2Q1
Iterated calls of array_splice() seems like a great way to go. Here is a cleaner version of István Őri's answer. Subtracting from 5 removes the need to use the modulus operator.
Code: (Demo)
$array = range(1, 10);
$chunks = [];
$chunkSize = 3;
while ($array) {
$chunkSize = 5 - $chunkSize;
$chunks[] = array_splice($array, 0, $chunkSize);
}
var_export($chunks);
This snippet modifies $array as it iterates. array_splice() keeps removing elements from the front of the array. Eventually the array will become empty and the while() condition will fail -- breaking the loop.
You could use this, it isn't the most elegant, but it will just do the trick for you - and you can modify it nicely and adapt it to suit your purposes further:
<?php
$originalArray = array(0,1,2,3,4,5,6,7,8,9);
$counter=count($originalArray);
$isTwo=true;
$newArray=array();
$arrElement=0;
$i=0;
while($i<$counter)
{
if($isTwo)
{
$newArray[$arrElement]= array();
for($j=0; $j<2; $j++)
{
$newArray[$arrElement][$j]=$originalArray[$i+$j];
}
$i+=2;
$isTwo=false;
$arrElement++;
}
else
{
$newArray[$arrElement]= array();
for($j=0; $j<3; $j++)
{
$newArray[$arrElement][$j]=$originalArray[$i+$j];
}
$i+=3;
$isTwo=true;
$arrElement++;
}
}
var_dump($newArray);
?>
Output:
array(4) {
[0]=>
array(2) {
[0]=>
int(0)
[1]=>
int(1)
}
[1]=>
array(3) {
[0]=>
int(2)
[1]=>
int(3)
[2]=>
int(4)
}
[2]=>
array(2) {
[0]=>
int(5)
[1]=>
int(6)
}
[3]=>
array(3) {
[0]=>
int(7)
[1]=>
int(8)
[2]=>
int(9)
}
}
$tobechunked_arr = array(0,1,2,3,4,5,6,7,8,9);
$chunk_size_arr = array(3,2,3,2);
$j = 0;
foreach($chunk_size_arr as $key => $val)
{
for($i = 0; $i < $val; $i++)
{
$result_arr[$key][] = $tobechunked_arr[$j];
$j++;
}
}
echo "<pre>";
print_r($result_arr);
try this
<?php
$input_array = array('a', 'b', 'c', 'd', 'e');
print_r(array_chunk($input_array, 2));
print_r(array_chunk($input_array, 2, true));
?>
Update
<?php
$myArray = array("abc","def","ghi","jkl","mno","pqr","stu","vwx","yz");
$newArray = array_chunk($myArray, 2, false);
// Now process the multidimensional array made from array_chunk()
$i = 0;
foreach ($newArray as $inner_array) {
$i++;
echo "<h2>Chunk $i</h2>";
while (list($key, $value) = each($inner_array)) {
echo "$key: $value <br />";
}
}
?>
Output
Chunk 1
0: abc
1: def
Chunk 2
0: ghi
1: jkl
Chunk 3
0: mno
1: pqr
Chunk 4
0: stu
1: vwx
Chunk 5
0: yz

Adding arrays in php

Arrays have been comprehensively covered but am still stumped about how to go around this. I have two arrays which i want to merge without overwriting duplicate keys i.e.
Array1
(
[0] => 0
[1] => 1
[2] => 1
[3] => 1
[4] => 1
[5] => 0
[6] => 0
)
+
Array2
(
[0] => 0
[1] => 0
[2] => 0
[3] => 0
[4] => 0
[5] => 0
[6] => 1
)
my ideal result is
Array1 + Array2
(
[0] => 0
[1] => 1
[2] => 1
[3] => 1
[4] => 1
[5] => 0
[6] => 1
)
How would i do this? I've tried using + but it gives the first array as the result
What you want to do is to map both arrays into single array, containing max value from two respective values, like that:
$array1 = array(0, 1, 1, 1, 1, 0, 0);
$array2 = array(0, 0, 0, 0, 0, 0, 1);
$result = array_map('max', $array1, $array2);
See the result here: http://ideone.com/clone/MN568
It looks like that:
array(7) {
[0]=>
int(0)
[1]=>
int(1)
[2]=>
int(1)
[3]=>
int(1)
[4]=>
int(1)
[5]=>
int(0)
[6]=>
int(1)
}
array_merge() does not overwrite duplicate elements that have numeric keys.
Given the arrays are of the same length:
function bitwise_or_arrays($arr1, $arr2) {
$result = array();
for ($i = 0; $i < count($arr1); $i++) {
$result[$i] = $arr1 | $arr2;
}
return $result;
}
If you are looking for the greater (nonzero) of the two arrays, you can iterate like so:
$array1 = array(1,0,0,1,1,1);
$array2 = array(0,0,1,0,0,1);
$newarr = array();
foreach ($array1 as $k => $v) {
$newarr[$k] = max($array1[$k], $array2[$k]);
}
print_r($newarr);
Array
(
[0] => 1
[1] => 0
[2] => 1
[3] => 1
[4] => 1
[5] => 1
)
If what you need is to add the values, use:
$newarr = array();
foreach ($array1 as $k => $v) {
$newarr[$k] = $array1[$k] + $array2[$k];
}
Just for fun (although in your case with 0 and 1 values it works :)
$array1 = array(0, 1, 1, 1, 1, 0, 0);
$array2 = array(0, 0, 0, 0, 0, 0, 1);
$str1 = implode('', $array1);
$str2 = implode('', $array2);
$result = str_split($str1 | $str2);
Sorry for this variant, I know it's crazy, but just couldn't not to post it. Arrays look like bit masks 0111100 and 0000001. So just using bitwise | operator.
So result:
Array
(
[0] => 0
[1] => 1
[2] => 1
[3] => 1
[4] => 1
[5] => 0
[6] => 1
)
If what your looking is to combine them use array_combine().
$a = array('green', 'red', 'yellow');
$b = array('avocado', 'apple', 'banana');
$c = array_combine($a, $b);
print_r($c);
//*output:
array(
[green] => avocado
[red] => apple
[yellow] => banana
)
here's how to merge array:
$beginning = 'foo';
$end = array(1 => 'bar');
$result = array_merge((array)$beginning, (array)$end);
print_r($result);
//output:
Array(
[0] => foo
[1] => bar
)
heres how to add values
$a = array(0=>1, 1=>2, 2=>3, 3=>4);
$b = array(0=>5, 1=>6, 2=>7, 3=>8);
$c = $a[0] += $b[0];
print_r($c);//output: 6
im not a guru on php but i hope this helps you even just abit.
Just for the fun of it:
$array1 = array(0,1,1,1,1,0,0);
$array2 = array(0,0,0,0,0,0,1);
$array3 = str_split(decbin(bindec(implode('',$array1)) | bindec(implode('',$array2))));
var_dump($array3);
Unfortunately it trims leading zeroes
Using
$array3 = str_split(str_pad(decbin(bindec(implode('',$array1)) | bindec(implode('',$array2))),count($array1),'0',STR_PAD_LEFT));
will restore leading zeroes, but doesn't feel as clean

Categories