Change the all the keys in a array in php - php

So I am playing around with arrays and I want to replace all of the keys in the array, so I have this array:
$array = array(1,5,8,0);
and this is how I replace the keys:
function recursive_change_key($arr, $set) {
if (is_array($arr) && is_array($set)) {
$newArr = array();
foreach ($arr as $k => $v) {
$key = array_key_exists( $k, $set) ? $set[$k] : $k;
$newArr[$key] = is_array($v) ? recursive_change_key($v, $set) : $v;
}
return $newArr;
}
return $arr;
}
$length = sizeof($array);
for($i = 0; $i < $length; $i++)
{
$people = recursive_change_key($array, array($i => "A"));
}
echo '<pre>';
print_r($people);
echo '</pre>';
So what I am trying to do is to replace all the array keys with A, but this is the result what I get:
And this is the result what I want:
(sorry for the bad editing)
I don't know what I am doing wrong. Could you please help?

The result you want is not possible to get. There cannot be several entries with the same key. For example, imagine you have general array $myArray, is it possible to have 3 $myArray[0] ? The answer is no and the same situation is with associative array.

Related

How to replace array value with another array value using php?

I have 2 arrays as follows:
$arr = array('one.jpg', 'two.jpg', 'three.jpg');
$arr1 = array('', 'five.jpg', '');
Now I want to make these two arrays to one array with following value:
$newArray = array('one.jpg', 'five.jpg', 'three.jpg');
How can I do this using PHP?
Use array_filter to remove the empty values.
Use array_replace to replace the values from the first array with the remaining values of the 2nd array.
$arr1=array_filter($arr1);
var_dump(array_replace($arr,$arr1));
Assuming you want to overwrite entries in the first array only with truthy values from the second:
$newArray = array_map(function ($a, $b) { return $b ?: $a; }, $arr, $arr1);
You can iterate through array and check value for second array :
$arr = array('one.jpg', 'two.jpg', 'three.jpg');
$arr1 = array('', 'five.jpg', '');
$newArray =array();
foreach ($arr as $key => $value) {
if(isset($arr1[$key]) && $arr1[$key] != "")
$newArray[$key] = $arr1[$key];
else
$newArray[$key] = $value;
}
var_dump($newArray);
Simple solution using a for loop, not sure whether there is a more elegant one:
$arr = array('one.jpg', 'two.jpg', 'three.jpg');
$arr1 = array('', 'five.jpg', '');
$newArray = array();
$size = count($arr);
for($i = 0; $i < $size; ++$i) {
if(!empty($arr1[$i])){
$newArray[$i] = $arr1[$i];
} else {
$newArray[$i] = $arr[$i];
}
}

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);
?>

Filter or Sorting multidimensional arrays in PHP

If i have two array as following:
$array1 = array(array('id'=>11,'name'=>'Name1'),array('id'=>22,'name'=>'Name2'), array('id'=>33,'name'=>'Name3'),array('id'=>44,'name'=>'Name4'),array('id'=>55,'name'=>'Name5'));
$array2 = array(array('id'=>22,'name'=>'Name2'),array('id'=>55,'name'=>'Name5'));
My expect result, the array2 should be always at the beginning :
$newarray = array(array('id'=>22,'name'=>'Name2'),array('id'=>55,'name'=>'Name5'), array('id'=>11,'name'=>'Name1'), array('id'=>33,'name'=>'Name3'),array('id'=>44,'name'=>'Name4'));
My current solution is using two for loops:
foreach($array2 as $Key2 => $Value2) {
foreach($array1 as $Key1 => $Value1){
if($Value1['id'] != $Value2['id']) {
//push array
}
}
}
Edit:
The result "$newarray" should not include the duplicate ids from array1.
But i am looking for a faster and simpler solution.
SOLUTION:
$a1 = array();
foreach ($array1 as $v) $a1[$v['uuid']] = $v;
$a2 = array();
foreach ($array2 as $v) $a2[$v['uuid']] = $v;
$filtered = array_values(array_diff_key($a1, $a2));
//print_r($filtered);
$newarray = array_merge($array2, $filtered);
Thank you guys!!!!
Thanks.
Regards Jack
you want $new_array = array_merge($array2, $array1); puts the second array onto the end of the first one
You can use array_merge() function for that, like this:
$newarray = array_merge($array2, $array1);
I am not sure about your requirement but to sort multi-dimensional array on some specific key
You need to use usort function
Try the code below:
$cmp = function ($a, $b){
$a_val = $a['id'];
$b_val = $b['id'];
if ( $a_val == $b_val) {
return 0;
}
return ($a_val < $b_val) ? -1 : 1;
};
usort($array2,$cmp);
$array2 will be sorted by 'id'

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.

Merge every other array php

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);

Categories