Compare and replace values in array - php

I need compare 2 arrays , the first array have one order and can´t change , in the other array i have different values , the first array must compare his id with the id of the other array , and if the id it´s the same , take the value and replace for show all in the same order
For Example :
$array_1=array("1a-dogs","2a-cats","3a-birds","4a-people");
$array_2=array("4a-walking","2a-cats");
The Result in this case i want get it´s this :
"1a-dogs","2a-cats","3a-birds","4a-walking"
If the id in this case 4a it´s the same , that entry must be modificate and put the value of other array and stay all in the same order
I do this but no get work me :
for($fte=0;$fte<count($array_1);$fte++)
{
$exp_id_tmp=explode("-",$array_1[$fte]);
$cr_temp[]="".$exp_id_tmp[0]."";
}
for($ftt=0;$ftt<count($array_2);$ftt++)
{
$exp_id_targ=explode("-",$array_2[$ftt]);
$cr_target[]="".$exp_id_targ[0]."";
}
/// Here I tried use array_diff and others but no can get the results as i want
How i can do this for get this results ?

Maybe you could use the array_udiff_assoc() function with a callback

Here you go. It's not the cleanest code I've ever written.
Runnable example: http://3v4l.org/kUC3r
<?php
$array_1=array("1a-dogs","2a-cats","3a-birds","4a-people");
$array_2=array("4a-walking","2a-cats");
function getKeyStartingWith($array, $startVal){
foreach($array as $key => $val){
if(strpos($val, $startVal) === 0){
return $key;
}
}
return false;
}
function getMergedArray($array_1, $array_2){
$array_3 = array();
foreach($array_1 as $key => $val){
$startVal = substr($val, 0, 2);
$array_2_key = getKeyStartingWith($array_2, $startVal);
if($array_2_key !== false){
$array_3[$key] = $array_2[$array_2_key];
} else {
$array_3[$key] = $val;
}
}
return $array_3;
}
$array_1 = getMergedArray($array_1, $array_2);
print_r($array_1);

First split the 2 arrays into proper key and value pairs (key = 1a and value = dogs). Then try looping through the first array and for each of its keys check to see if it exists in the second array. If it does, replace the value from the second array in the first. And at the end your first array will contain the result you want.
Like so:
$array_1 = array("1a-dogs","2a-cats","3a-birds","4a-people");
$array_2 = array("4a-walking","2a-cats");
function splitArray ($arrayInput)
{
$arrayOutput = array();
foreach ($arrayInput as $element) {
$tempArray = explode('-', $element);
$arrayOutput[$tempArray[0]] = $tempArray[1];
}
return $arrayOutput;
}
$arraySplit1 = splitArray($array_1);
$arraySplit2 = splitArray($array_2);
foreach ($arraySplit1 as $key1 => $value1) {
if (array_key_exists($key1, $arraySplit2)) {
$arraySplit1[$key1] = $arraySplit2[$key1];
}
}
print_r($arraySplit1);
See it working here:
http://3v4l.org/2BrVI

$array_1=array("1a-dogs","2a-cats","3a-birds","4a-people");
$array_2=array("4a-walking","2a-cats");
function merge_array($arr1, $arr2) {
$arr_tmp1 = array();
foreach($arr1 as $val) {
list($key, $val) = explode('-', $val);
$arr_tmp1[$key] = $val;
}
foreach($arr2 as $val) {
list($key, $val) = explode('-', $val);
if(array_key_exists($key, $arr_tmp1))
$arr_tmp1[$key] = $val;
}
return $arr_tmp1;
}
$result = merge_array($array_1, $array_2);
echo '<pre>';
print_r($result);
echo '</pre>';
This short code works properly, you'll get this result:
Array
(
[1a] => dogs
[2a] => cats
[3a] => birds
[4a] => walking
)

Related

Rank array values with possible duplicate values

I am trying to rank an array of values and maintain the order in the original array.
So for example:
(6,4,7,12,7) should return (2,1,3,4,3)
(12,17,5,27,5) should return (2,3,1,4,1)
(1,1,4,6) should return (1,1,2,3)
In each case the returned array has the rank of the corresponding element in the original array, and duplicate values will have the same rank.
$values = array(12,17,5,27,5);
$sorted_values = $values;
sort($sorted_values);
foreach ($values as $key => $value) {
foreach ($sorted_values as $sorted_key => $sorted_value) {
if ($value == $sorted_value) {
$rank_key = $sorted_key;
break;
}
}
echo $value . ' has rank: ' . $rank_key + 1 . '<br>';
}
A simple way would be to first rank the unique values (using array_unique() followed by sort()), then translate the original list by this newly rank list (more comments in the code)...
$source = [12,17,5,27,5];
$output = [];
// Copy to work array unique values
$rank = array_unique($source);
// Sort it to produce ranking order
sort($rank);
// Make the number the key with the order as the value
$rank = array_flip($rank);
// Translate the values using $rank
foreach ( $source as $element ) {
$output[] = $rank[$element]+1;
}
print_r($output);
gives...
Array
(
[0] => 2
[1] => 3
[2] => 1
[3] => 4
[4] => 1
)
Clone your array, sort the clone by values, while keeping the key associations.
Loop over the clone, and in classical “control break” fashion, compare the value of the current item to that of the previous one. Increase the rank by one, if they differ. Set that rank as new value under that key.
Sort the clone by keys.
$data = [12,17,5,27,5];
$clone = $data;
asort($clone);
$rank = 0;
$previous_value = null; // something that doesn't ever occur in your array values
foreach($clone as $key => $value) {
if($value !== $previous_value) {
$rank++;
}
$clone[$key] = $rank;
$previous_value = $value;
}
ksort($clone);
var_dump($data, $clone);
you need to sort your array
This may close to your answer:
<?php
$my_array=array(12,17,5,27,5);
$ordered_values = $my_array;
$rank=array();
rsort($ordered_values);
foreach ($ordered_values as $key => $value) {
foreach ($ordered_values as $ordered_key => $ordered_value) {
if ($value === $ordered_value) {
$key = $ordered_key;
break;
}
}
$rank[$value]=((int) $key + 1) ;
}
foreach($my_array as $key => $value)
{
echo $value.':'.$rank[$value].'<br>';
}
?>
function rankDuplicateArray(array $array): array
{
$copy = array_unique($array);
sort($copy);
$flipArray = array_flip($copy);
return array_map(function($v) use ($flipArray) {
return $flipArray[$v] + 1;
}, $array);
}

PHP/MYSQL Replace text of keys in array of dictionaries

I have a MYSQL query that fetches an array of dictionaries or results which are returned via JSON in an api. In some cases, I would like to change the name of the dictionary keys in the results array.
For example, in the following case:
$var = '[{"player":"Tiger Woods"},{"player":"Gary Player"}]';
I would like to change it to:
$var = '[{"golfer":"Tiger Woods"},{"golfer":"Gary Player"}]'
It is not practical in this case to change the mysql query so I'd just like to replace the word "player" with the word "golfer" for the keys without disturbing the values.
In the above example, I would not want to change Gary Player's name so just using str_replace does not seem like it would work.
Is there a way to change all of the keys from "player" to "golfer" without changing any of the values?
Here is the snippet you can use
$var = '[{"player":"Tiger Woods"},{"player":"Gary Player"}]';
// json decode the json string
$temp = json_decode($var, true);
$temp = array_map(function($item){
// combining key and values
return array_combine(['golfer'], $item);
}, $temp);
print_r($temp);
// or echo json_encode($temp);
Demo.
Some argue that foreach is fastest,
foreach($temp as $k => &$v){
$v = array_combine(['golfer'], $v);
}
print_r($temp);
Demo.
Little hardcoded if more than one keys in single array,
foreach ($temp as $k => &$v){
$v['golfer'] = $v['player'];
unset($v['player']);
}
print_r($temp);
Demo.
Using recursion
function custom($arr, $newKey, $oldKey)
{
// if the value is not an array, then you have reached the deepest
// point of the branch, so return the value
if (!is_array($arr)) {
return $arr;
}
$result = []; // empty array to hold copy of subject
foreach ($arr as $key => $value) {
// replace the key with the new key only if it is the old key
$key = ($key === $oldKey) ? $newKey : $key;
// add the value with the recursive call
$result[$key] = custom($value, $newKey, $oldKey);
}
return $result;
}
$var = '[{"player":"Tiger Woods"},{"player":"Gary Player"}]';
$temp = json_decode($var, true);
$temp = replaceKey($temp, 'golfer', 'player');
print_r($temp);
Demo & source.
Using json way,
function json_change_key($arr, $oldkey, $newkey) {
$json = str_replace('"'.$oldkey.'":', '"'.$newkey.'":', json_encode($arr));
return json_decode($json, true);
}
$temp = json_change_key($temp, 'player', 'golfer');
print_r($temp);
Demo
If you want multiple key replace, here is the trick,
$var = '[{"player":"Tiger Woods", "wins":"10","losses":"3"},{"player":"Gary Player","wins":"7", "losses":6}]';
$temp = json_decode($var, true);
function recursive_change_key($arr, $set)
{
if (is_array($arr) && is_array($set)) {
$newArr = [];
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;
}
$set = [
"player" => "golfers",
"wins" => "victories",
"losses" => "defeats"
];
$temp = recursive_change_key($temp, $set);
print_r($temp);
Demo.
$a = '[{"player":"Tiger Woods"},{"player":"Gary Player"}]';
$array = json_decode($a, true);
foreach($array as $key=>$value){
if(array_keys($value)[0] === "player"){
$array[$key] = ["golfer" => array_values($value)[0]];
};
}
echo json_encode($array);
you can write the value of the key to a new key and then delete the old.
renaming a key called "a" to "b", while keeping the value.
var json = {
"a" : "one"
}
json["b"] = json["a"];
delete json["a"];
for your example, just use this with a loop.
source: https://sciter.com/forums/topic/how-to-rename-the-key-of-json/

PHP Can't get the right format for array

I got stuck somehow on the following problem:
What I want to achieve is to merge the following arrays based on key :
{"Entities":{"submenu_id":"Parents","submenu_label":"parents"}}
{"Entities":{"submenu_id":"Insurers","submenu_label":"insurers"}}
{"Users":{"submenu_id":"New roles","submenu_label":"newrole"}}
{"Users":{"submenu_id":"User - roles","submenu_label":"user_roles"}}
{"Users":{"submenu_id":"Roles - permissions","submenu_label":"roles_permissions"}}
{"Accounting":{"submenu_id":"Input accounting data","submenu_label":"new_accounting"}}
Which needs to output like this:
[{"item_header":"Entities"},
{"list_items" :
[{"submenu_id":"Parents","submenu_label":"parents"},
{"submenu_id":"Insurers","submenu_label":"insurers"}]
}]
[{"item_header":"Users"},
{"list_items" :
[{"submenu_id":"New roles","submenu_label":"newrole"}
{"submenu_id":"User - roles","submenu_label":"user_roles"}
{"submenu_id":"Roles - permissions","submenu_label":"roles_permissions"}]
}]
[{"item_header":"Accounting"},
{"list_items" :
[{"submenu_id":"Input accounting data","submenu_label":"new_accounting"}]
}]
I have been trying all kinds of things for the last two hours, but each attempt returned a different format as the one required and thus failed miserably. Somehow, I couldn't figure it out.
Do you have a construction in mind to get this job done?
I would be very interested to hear your approach on the matter.
Thanks.
$input = array(
'{"Entities":{"submenu_id":"Parents","submenu_label":"parents"}}',
'{"Entities":{"submenu_id":"Insurers","submenu_label":"insurers"}}',
'{"Users":{"submenu_id":"New roles","submenu_label":"newrole"}}',
'{"Users":{"submenu_id":"User - roles","submenu_label":"user_roles"}}',
'{"Users":{"submenu_id":"Roles - permissions","submenu_label":"roles_permissions"}}',
'{"Accounting":{"submenu_id":"Input accounting data","submenu_label":"new_accounting"}}',
);
$input = array_map(function ($e) { return json_decode($e, true); }, $input);
$result = array();
$indexMap = array();
foreach ($input as $index => $values) {
foreach ($values as $k => $value) {
$index = isset($indexMap[$k]) ? $indexMap[$k] : $index;
if (!isset($result[$index]['item_header'])) {
$result[$index]['item_header'] = $k;
$indexMap[$k] = $index;
}
$result[$index]['list_items'][] = $value;
}
}
echo json_encode($result);
Here you are!
In this case, first I added all arrays into one array for processing.
I thought they are in same array first, but now I realize they aren't.
Just make an empty $array=[] then and then add them all in $array[]=$a1, $array[]=$a2, etc...
$array = '[{"Entities":{"submenu_id":"Parents","submenu_label":"parents"}},
{"Entities":{"submenu_id":"Insurers","submenu_label":"insurers"}},
{"Users":{"submenu_id":"New roles","submenu_label":"newrole"}},
{"Users":{"submenu_id":"User - roles","submenu_label":"user_roles"}},
{"Users":{"submenu_id":"Roles - permissions","submenu_label":"roles_permissions"}},
{"Accounting":{"submenu_id":"Input accounting data","submenu_label":"new_accounting"}}]';
$array = json_decode($array, true);
$intermediate = []; // 1st step
foreach($array as $a)
{
$keys = array_keys($a);
$key = $keys[0]; // say, "Entities" or "Users"
$intermediate[$key] []= $a[$key];
}
$result = []; // 2nd step
foreach($intermediate as $key=>$a)
{
$entry = ["item_header" => $key, "list_items" => [] ];
foreach($a as $item) $entry["list_items"] []= $item;
$result []= $entry;
}
print_r($result);
I would prefer an OO approach for that.
First an object for the list_item:
{"submenu_id":"Parents","submenu_label":"parents"}
Second an object for the item_header:
{"item_header":"Entities", "list_items" : <array of list_item> }
Last an object or an array for all:
{ "Menus: <array of item_header> }
And the according getter/setter etc.
The following code will give you the requisite array over which you can iterate to get the desired output.
$final_array = array();
foreach($array as $value) { //assuming that the original arrays are stored inside another array. You can replace the iterator over the array to an iterator over input from file
$key = /*Extract the key from the string ($value)*/
$existing_array_for_key = $final_array[$key];
if(!array_key_exists ($key , $final_array)) {
$existing_array_for_key = array();
}
$existing_array_for_key[count($existing_array_for_key)+1] = /*Extract value from the String ($value)*/
$final_array[$key] = $existing_array_for_key;
}

show only duplicate values from array without builtin function PHP

For example:
$arr = array(3,5,2,5,3,9);
I want to show only common elements i.e 3,5 as output.
Here's my attempt:
<?php
$arr = array(3,5,2,5,3,9);
$temp_array = array();
foreach($arr as $val)
{
if(isset($temp_array[$val]))
{
$temp_array[$val] = $val;
}else{
$temp_array[$val] = 0;
}
}
foreach($temp_array as $val2)
{
if($val2 > 0)
{
echo $val2 . ', ';
}
}
?>
--
Output --
3, 5,
Try the following:
$arr = array(3,5,2,5,3,9);
foreach($arr as $key => $val){
//remove the item from the array in order
//to prevent printing duplicates twice
unset($arr[$key]);
//now if another copy of this key still exists in the array
//print it since it's a dup
if (in_array($val,$arr)){
echo $val . " ";
}
}
Output:
3 5
Addition:
I guess that the reason you were asked to implement it yourself (without using built-in functions) was to avoid answers like:
$unique = array_unique($arr);
$dupes = array_diff_key( $arr, $unique );
$arrnew = array();
for($i=0;$i<count($arr);$i++)
{
for($j=$i+1;$j<count($arr);$j++)
{
if($arr[$i]==$arr[$j])
{
$arrnew[]=$arr[$j];
}
}
}

Create an array with duplicated value from an array (PhP)

I want to create an new array with duplicated MAX value from an array
and put other duplicate value in an other array
$etudiant = array ('a'=>'2','b'=>'5', 'c'=>'6', 'd'=>'6', 'e'=>'2');
and i want this result
$MaxArray = array ('c'=>'6', 'd'=>'6');
$otherarray1 = array ('a'=>'2', 'e'=>'2');
Thank you !
First, find the maximum value:
$etudiant = array ('a'=>'2','b'=>'5', 'c'=>'6', 'd'=>'6', 'e'=>'2');
$maxValue = max($etudiant);
Second, find values that appear more than once:
$dups = array_diff_assoc($etudiant, array_unique($etudiant));
Lastly, check the original arrays for values matching either $maxValue or values that are listed in $dups:
$MaxArray = $OtherArray = $ElseArray = array();
foreach ($etudiant as $key => $value) {
if ($value == $maxValue) {
$MaxArray[$key] = $value;
} else if (in_array($value, $dups)) {
$OtherArray[$key] = $value;
} else {
$ElseArray[$key] = $value;
}
}
You'll get:
$MaxArray: Array
(
[c] => 6
[d] => 6
)
$OtherArray: Array
(
[a] => 2
[e] => 2
)
Note: I wasn't sure if you wanted the $MaxArray to contain the maximum value elements only if it appears more than once in the source array. If so, just change the max call to:
$maxValue = max($dups);
You can use array_values(array_intersect($array1, $array2)) to get duplicated values, and then make a loop to capture the keys which have those values and store them into another array.
$dups = array_values(array_intersect($array1, $array2))
$max = max($dups);
$result = array();
foreach ($array1 as $key => $value){
if (in_array($value, $dups)) {
$result[$key] = $value;
}
}
foreach ($array2 as $key => $value){
if (in_array($value, $dups)) {
$result[$key] = $value;
}
}
$maxArray = array();
foreach ($dups as $key => $value) {
if ($value == $max){
$maxArray[$key] = $value;
}
}
// results are in $dups and $maxArray
If you are looking to find elements with the min and max values from an array, the following will work.
// get min keys
$min_value = min($etudiant);
$min_keys = array_keys($etudiant, $min_value);
// get max keys
$max_value = max($etudiant);
$max_keys = array_keys($etudiant, $max_value);
You could then either rebuild your example arrays with these keys in a loop. Or access them directly, i.e. $etudiant[$min_keys].
Check out the documentation for array_keys, min, max

Categories