PHP: Transformation of array - php

There is the following array:
arr1 = array(array('xxx',3),array('yyy',2));
I need to transform it into the array arr2, where the number of occurrence of each entry is equal to the 2nd column value in array arr1. For instance, for the above given arr1, arr2 should be the following:
arr2 = array(array('xxx'),array('xxx'),array('xxx'),array('yyy'),array('yyy'));
I wrote the following code, but my question is: Is it possible to do the same in a simpler way?
for ($i=0; $i<count($arr1); $i++) {
for ($j=0; $j<$arr1[i][1]; $j++) {
$arr2[] = array($arr1[0]);
}
}

I think a foreach is simpler and easier to read.
$arr1 = array(array('xxx', 3), array('yyy', 2));
$arr2 = array();
foreach ($arr1 as $arr)
{
for ($i = 0; $i < $arr[1]; $i++)
{
$arr2[] = array($arr[0]);
}
}

foreach ($arr1 as $entry) {
$arr2[] = array_fill(0, $entry[1], array($entry[0]));
}
$arr2 = call_user_func_array('array_merge', $arr2);
I wouldn't use it though. It's much less readable.

Related

PHP array keys as nth value

I have an Associative array as
$array = Array([0]=>a[1]=>b[2]=c[3]=>d);
I need to build an array from this array where the the first key becomes a and the value becomes b & 2nd key becomes c and value becomes d.
Output should be:
$finalarray = Array([a]=>b,[c]=>d);
I have tried this following code:
foreach($array as $key=>$value){
$arr[$value] = array_slice($array, 1, 1);
$finalarray[] = $arr;
}
Please help me with this!
The best way is to loop on your first array, but to skip one value on two:
$array = array("a", "b", "c", "d");
$finalArray = array();
for ($i = 0; $i < count($array); $i+=2) {
$finalArray[$array[$i]] = $array[$i + 1];
}
This may help:
$a = array('a','b','c','d'); $b = array();
$length = count(a)%2 ? count($a)-1 : count($a);
for($i=0; $i<$length; $i++){
$b[$a[$i]] = $a[++$i];
}
var_dump($a,$b);
Little changed your code:
$i=0;
foreach($array as $key=>$value){
$value_2=$value++;
if($i%2==0)
$arr[$value_2] =$value;
$i++;
//$finalarray[] = $arr;
}
echo"<pre>";
print_r($arr);
If your array is associative , below code may help you
<?php
$array = array(0=>'a',1=>'b',2=>'c',3=>'d');
$new_array = array();
for($i=0;$i<count($array);$i+=2)
{
$new_array[$array[$i]] = $array[$i+1];
}
print_r($new_array);
?>

PHP Merging arrays with for loops without using array_merge function

I am learning more about for loops and would like to see how do you merge arrays using only for loops and not using built-in PHP functions such as array_merge().
I know you can use foreach to do this, but how would this work using only for loops and not foreach?
foreach example:
$array1 = ['judas', 'john', 'michael'];
$array2 = ['fernando', 'jsamine', 'sam', 'walter'];
$array3 = ['judas', 'john', 'mike', 'steve'];
foreach ([$array1, $array2, $array3] as $arr) {
foreach ($arr as $values) {
...
}
}
Yes, you can do this using just for loops.
$array1 = ['judas', 'john', 'michael'];
$array2 = ['fernando', 'jsamine', 'sam', 'walter'];
$array3 = ['judas', 'john', 'mike', 'steve'];
$all_arrays = [$array1, $array2, $array3];
$merged = [];
for ($i = 0; $i < 3; $i++) {
$arr = $all_arrays[$i];
$x = count($arr);
for ($j=0; $j < $x; $j++) {
// Using the value as the key in the merged array ensures
// that you will end up with distinct values.
$merged[$arr[$j]] = 1;
}
}
// You could use array_keys() to do get the final result, but if you
// want to use just loops then it would work like this:
$final = [];
$x = count($merged);
for ($i=0; $i < $x; $i++) {
$final[] = key($merged);
next($merged);
}
var_dump($final);
key() and next() ARE php functions. But I really do not know of a way to get to the keys without using either foreach or some php function.
Iterate each array on its own:
foreach($array2 as $v)
if(!in_array($v, $array1))
$array1[] = $v;
foreach($array3 as $v)
if(!in_array($v, $array1))
$array1[] = $v;
Or simply use array_merge() - there is no reason for do not do it.
$a=array('1','2','3','4','5');
$b=array('a','b','c','d','e');
$c=count($b);
for($i=0; $i<$c; $i++)
{
$a[]=$b[$i]; // each element 1 by 1 store inside the array $a[]
}
print_r($a);
function arrayMerge(array $arrays) {
$mergeArray = [];
foreach ($arrays as $key => $array) {
foreach($array as $finalArray) {
$mergeArray[] = $finalArray;
}
}
return $mergeArray;
}
$array1 = [
'Laravel', 'Codeigniter', 'Zend'
];
$array2 = [
'Node js', 'Vue js', 'Angular js'
];
$array3 = [
'Python', 'Django', 'Ruby'
];
print_r(arrayMerge([$array1, $array2, $array3]));
$arr1 = array(1,2,3,4,5);
$arr2 = array(2,5,6,7,8);
$allval = array();
foreach($arr2 as $key=>$val){
$arr1[] = $val;
}
foreach($arr1 as $k=>$v){
if(!in_array($v,$allval)){
$allval[] = $v;
}
}
echo "<pre>"; print_R($allval);

Determining duplicate letter counts between an array of strings

I have an array of strings of random letters, and I need to know which letters are consistent between the array members. The count of the letters are important.
My method right now is loop through the array, doing a split, then looping through the spitted string to count the occurrences of each letter, then update the array with letter => count
Then do an array_reduce that creates a new array of members who only occur in all arrays. But, it's not working.
<?
$a[] = "emaijuqqrauw";
$a[] = "aaeggimqruuz";
$a[] = "aabimqrtuuzw";
$a[] = "aacikmqruuxz";
$a[] = "aacikmqruuxz";
$a[] = "aaciimqruuxy";
foreach($a as $b){
$n = str_split($b, 1);
foreach($n as $z){
$arr[$z] = substr_count($b, $z);
}
ksort($arr);
$array[] = $arr;
unset($arr);
}
$n = array_reduce($array, function($result, $item){
if($result === null){
return $item;
}else{
foreach($item as $key => $val){
if(isset($result[$key])){
$new[$key] = $val;
}
}
return $new;
}
});
foreach($n as $key => $val){
echo str_repeat($key, $val);
}
This returns aaiimqruu - which is kinda right, but there's only 2 i's in the last element of the array. There's only one i in the rest. I'm not sure how to break that down farther and get it to return aaimqruu- which I'll then pop into a SQL query to find a matching word, aquarium
There's array_intersect(), which is most likely what you'd want. Given your $a array, you'd do something like:
$a = array(.... your array...);
$cnt = count($a);
for($i = 0; $i < $cnt; $i++) {
$a[$i] = explode('', $a[$i]); // split each string into array of letters
}
$common = $a[0]; // save the first element
for($i = 1; $i < $cnt; $i++) {
$common = array_intersect($common, $a[$i]);
}
var_dump($common);
How about you do it this way? Finds out the occurrence of an item throughout the array.
function findDuplicate($string, $array) {
$count = 0;
foreach($array as $item) {
$pieces = str_split($item);
$pcount= array_count_values($pieces);
if(isset($pcount[$string])) {
$count += $pcount[$string];
}
}
return $count;
}
echo findDuplicate("a",$a);
Tested :)
Gives 12, using your array, which is correct.
Update
My solution above already had your answer
$pieces = str_split($item);
$pcount= array_count_values($pieces);
//$pcount contains, every count like [a] => 2
Seems like array_reduce is the best function for what this purpose, however I just didn't think of adding a conditional to give me the desired effect.
$new[$key] = ($result[$key] > $val) ? $val : $result[$key];
to replace
$new[$key] = $val;
did the trick.

php foreach loop

I have two arrays in my code.
Need to perform a foreach loop on both of these arrays at one time. Is it possible to supply two arguments at the same time such as foreach($array1 as $data1 and $array2 as $data2)
or something else?
If they both the same keys, you can do this:
foreach($array1 as $key=>data1){
$data2 = $array2[$key];
}
Assuming both have the same number of elements
If they both are 0-indexed arrays:
foreach ($array_1 as $key => $data_1) {
$data_2 = $array_2[$key];
}
Otherwise:
$keys = array_combine(array_keys($array_1), array_keys($array_2));
foreach ($keys as $key_1 => $key_2) {
$data_1 = $array_1[$key_1];
$data_2 = $array_2[$key_2];
}
Dont use a foreach. use a For, and use the incremented index, eg. $i++ to access both arrays at once.
Are both arrays the same size always?
Then this will work:
$max =sizeof($array);
for($i = 0; $i < $max; $i++)
array[$i].attribute
array2[$i].attribute
If the arrays are different sizes, you may have to tweak your approach. Possibly use a while.
iterative methods:
http://php.net/manual/en/control-structures.while.php
http://php.net/manual/en/control-structures.for.php
http://php.net/manual/en/control-structures.do.while.php
use for or while loop e.g.
$i = 0;
while($i < count($ar1) && $i < count($ar2) ) // $i less than both length !
{
$ar1Item = $ar1[$i];
$ar2Item = $ar2[$i];
$i++;
}
No to my knowledge with foreach, but can be easily done with for:
<?php
$cond1 = 0<count($array1);
$cond2 = 0<count($array2);
for ($i=0;$cond1 || $cond2;$i++)
{
if ($cond1)
{
// work with $array1
}
if ($cond2)
{
// work with $array2
}
$cond1 = 0<count($array1);
$cond2 = 0<count($array2);
}
?>

How do I select random values from an array in PHP?

I have an array of objects in PHP. I need to select 8 of them at random. My initial thought was to use array_rand(array_flip($my_array), 8) but that doesn't work, because the objects can't act as keys for an array.
I know I could use shuffle, but I'm worried about performance as the array grows in size. Is that the best way, or is there a more efficient way?
$result = array();
foreach( array_rand($my_array, 8) as $k ) {
$result[] = $my_array[$k];
}
$array = array();
shuffle($array); // randomize order of array items
$newArray = array_slice($array, 0, 8);
Notice that shuffle() function gives parameter as a reference and makes the changes on it.
You could use array_rand to pick the keys randomly and a foreach to gather the objects:
$objects = array();
foreach (array_rand($my_array, 8) as $key) {
$objects[] = $my_array[$key];
}
What about?:
$count = count($my_array);
for ($i = 0; $i < 8; $i++) {
$x = rand(0, $count);
$my_array[$x];
}
I just found this in our code and was hoping to find a more readable solution:
$rand = array_intersect_key($all, array_flip(array_rand($all, $count)));
You can get multiple random elements from an array with this function:
function getRandomElements(array $array): array
{
$result = [];
$count = count($array);
for ($i = 0; $i < rand(0, $count); $i++) {
$result[] = rand(0, $count);
}
$result = array_unique($result);
sort($result);
return $result;
}

Categories