PHP comparing 2 arrays - php

I've stuck in some certain problem, I've got two arrays which are the output of some other methods:
$firstArray = ['Johny Mao'=>'A', 'Kate Young'=>'B', 'Adam Mink'=>'C'];
$secondArray = [
['Johny Mao','A'],
['Kate Young', 'B'],
['Adam Mink', 'C']
];
How should I change these two arrays in order two compare them?
I need to know wheter they consist the same information.
Probably I should use array_diff methods but first I need to change arrays structure to be able to compar them.
Hope expressed clearly :)

Create a new array (or modify the second array) to key/value pairs matching the first array
$newArray = array_combine(
array_column($secondArray, 0),
array_column($secondArray, 1)
);
and then do your comparison

The comments are spot on. This is the developers idea.
Without using array_diff or something:
function array_are_same($firstarray,$secondarray){
foreach ($firstarray as $key => $value) {
if (!array_key_exists($key, $secondarray)
|| $secondarray[$key] !== $value){
return false;
}
return true;
}
}

You could do something like this, assuming you don't need to check if elements in first array aren't in second array.
function areArraysEqual($firstArray, $secondArray)
{
if(count($firstArray) != count($secondArray))
{
return false;
}
foreach($secondArray as $key => $value)
{
if(!isset($firstArray[$value[0]]) || $firstArray[$value[0]] != $value[1])
{
return false;
}
}
return true;
}
$firstArray = ['Johny Mao'=>'A', 'Kate Young'=>'B', 'Adam Mink'=>'C'];
$secondArray = [
['Johny Mao','A'],
['Kate Young', 'B'],
['Adam Mink', 'C']
];
$result = areArraysEqual($firstArray, $secondArray);
var_dump($result);
Edit:
This code below should now take into account if elements in the first array aren't in the second array.
<?php
function isValueIn2dArray(&$array, $secondDimensionKey, $value)
{
foreach($array as $key => $array2)
{
if($array2[$secondDimensionKey] == $value)
{
return true;
}
}
return false;
}
function areArraysEqual($firstArray, $secondArray)
{
if(count($firstArray) != count($secondArray))
{
return false;
}
foreach($secondArray as $key => $value)
{
if(!isset($firstArray[$value[0]]) || $firstArray[$value[0]] != $value[1])
{
return false;
}
}
foreach($firstArray as $key => $value)
{
if(!isValueIn2dArray($secondArray, 0, $key))
{
return false;
}
}
return true;
}
$firstArray = ['Johny Mao'=>'A', 'Kate Young'=>'B', 'Adam Mink'=>'C'];
$secondArray = [
['Johny Mao','A'],
['Kate Young', 'B'],
['Adam Mink', 'C']
];
$result = areArraysEqual($firstArray, $secondArray);
var_dump($result);

Related

Incrementing value of an array from another array

I have 2 arrays
$array1 = array(22,193,124);
$array2 = array(array('id'=>22, 'count'=> 1), array('id'=>124, 'count'=>2));
Now I need to search in $array2 for id from $array1 and if found to increment the count value and also add to the array the one's which are not found with a count as 1 so my resulting array would be
$arr = array(array('id'=>22, 'count'=> 2), array('id'=>124, 'count'=>3), array('id'=>193, 'count'=>1));
any help would be appreciated
The current code which I tried is
if($array2){
foreach($array1 as $array){
if(in_array($array, array_column($array2, 'id'))){
$wa_array['count'] += 1;
} else {
$wa_array['id'] = $array;
$wa_array['count'] = 1;
}
}
} else {
foreach($array1 as $array){
$wa_array['id'] = $array;
$wa_array['count'] = 1;
}
}
This may be something you are looking for -
$array1 = array(22,193,124);
$array2 = array(array('id'=>22, 'count'=> 1), array('id'=>124, 'count'=>2));
foreach($array1 as $key=>$digit)
{
$keyFound = array_search($digit, array_column($array2, 'id'));
if($keyFound === false)
{
array_push($array2, ['id'=>$digit, 'count'=>1]);
}
else
{
$array2[$keyFound]['count']++;
}
}
print_r($array2);
The question is not so clear, so I will go with my understanding : You need to check if values inside the first array are in the second array. If yes, increment the count value of that second array, if not, create that element with the value of 1.
This code is not tested, hope this can help find the good solution.
foreach($array1 as $value){
searchForId($value,$array2);
}
function searchForId($id, $array) {
foreach ($array as $key => $val) {
if ($val['id'] === $id) {
$val['count'] += 1;
}else{
array_push(array('id'=>$id,'count'=>1))
}
}
return null;
}
you should loop through $array2, not $array1. Finding the value in array_column($array2, 'id') doesn't tell you the index of the array element to increment.
foreach ($array2 as &$item) {
if (in_array($item['id'], $array1)) {
$item['count']++;
}
}
Note that you have to use &$item to make this a reference to the original array element, so that modifying it will update $array2. Otherwise, $item would be a copy of the array element.
If $array1 is large, it would be better to convert it to an associative array so you can test membership more efficiently.
$array1_assoc = array_flip($array1);
Then the test in the loop becomes:
if (isset($array1_assoc[$item['id']]) {
Check this one. NOTE: But this has O(n^2) complexity.
$array1 = [22,193,124];
$array2 = [['id'=>22, 'count'=> 1], ['id'=>124, 'count'=>2]];
foreach ($array1 as $value) {
$isFound = false;
foreach ($array2 as &$item) {
if ($value == $item['id']) {
$item['count']++;
$isFound = true;
continue;
}
}
if ($isFound == false) {
$array2 [] = ['id'=>$value, 'count'=> 1];
}
}
var_dump($array2);

PHP Transform mixed sequential and associative array to associative array

I would like to build $goal array from $initial only. Any ideas? Thank you
Edit : the question could be how to differentiate associative parts from sequential ones.
$intial=[
"one",
"two"=>"myTwo",
"three",
"four"=>"myFour"
];
$goal=[
"one"=>null,
"two"=>"myTwo",
"three"=>null,
"four"=>"myFour"
];
The 'sequential' parts will have numeric keys, so if your 'associative' keys will always be strings, you could use that to differentiate:
$goal = [];
foreach ($initial as $key => $value) {
if (is_numeric($key)) {
$goal[$value] = null;
} else {
$goal[$key] = $value;
}
}
$goal = [];
foreach($initial as $key => $val){
if(isset($val){
$goal[$key] = $val;
}else{
$goal[$key] = $key;
}
}

return row of array where key=value in multi dimentional array

array:
array(
['name'=>'kevin','value'=>'10'],
['name'=>'sam','value'=>'20']
);
how can i return value where name='sam' for example ?
and what how can i do it in even deeper array
array(
[0]=>array( 'inputs'=>
array(['name'=>'kevin','value'=>'10'],['name'=>'sam','value'=>'20']
),
[1]=>array( 'inputs'=>
array(['name'=>'kim','value'=>'10'],['name'=>'kirki','value'=>'20']
)
);
you need a recursive array_search - all answers above handle an exact amount of depth (in this case 2) only.
something like
function recursive_array_search($needle,$haystack) {
foreach ($haystack as $key=>$value) {
if ($needle===$value OR (is_array($value) && recursive_array_search($needle,$value) !== false)) {
return $value['value'];
}
}
return false;
}
recursive_array_search('sam', $start_array);
$arr = array(
array("name"=>"A","info"=>"one"),
array("name"=>"B","info"=>"two"),
array("name"=>"C","info"=>"three")
);
foreach($arr as $v){
if ($v['name']==="A"){
echo $v['info'];
}
}
In Deep Level
$arr = array(
array("input"=>array(
"name"=>"A",
"info"=>"one"
)),
array("input"=>array(
"name"=>"B",
"info"=>"Two"
))
);
foreach($arr as $subarr){ // First foreach iterate through arrays and next foreach iterate through values of each sub array
foreach($subarr as $v){
if ($v['name']==="A"){
echo $v['info'];
}
}
}
for($i=0;$i<count($array);$i++)
{
if($array['name']=="sam")
{
echo $array['value'];
}
}
and for next array you can do like this....
for($i=0;$i<count($array);$i++)
{
for($j=0;$j<count($array[$i]['inputs']);$j++)
{
if($array[$i]['inputs'][$j]['name']=="sam")
{
echo $array[$i]['inputs'][$j]['info'];
}
}
}
$new_array = array();
foreach ($old_array as $value) {
$new_array[$value['name']] = $value['value'];
}
var_dump($new_array['kevin']); // prints 10

Join two or more arrays of arrays

Suppose I have two arrays like the following:
$arr2 = array(array("first", "second"), array("third", "fourth"));
$arr3 = array(array("fifth", "sixth", "seventh"), array("eighth", "ninth"), array("tenth", "eleventh"));
And I want a result like this:
$arr4 = array("first", "second", "third", "fourth", "fifth", "sixth", "seventh","eighth", "ninth","tenth", "eleventh" );
How to do that? in PHP
What you want to is flatten and combine the arrays. There's a nice function for flattening in the comments in the PHP manual of array_values, http://www.php.net/manual/en/function.array-values.php#104184
Here's the code:
/**
* Flattens an array, or returns FALSE on fail.
*/
function array_flatten($array) {
if (!is_array($array)) {
return FALSE;
}
$result = array();
foreach ($array as $key => $value) {
if (is_array($value)) {
$result = array_merge($result, array_flatten($value));
}
else {
$result[$key] = $value;
}
}
return $result;
}
Just run this on array($arr2, $arr3).
function flatten($ar,&$res) {
if (is_array($ar))
foreach ($ar as $e) flatten($e,$res);
else
$res[]=$ar;
}
$arr2 = array(array("first", "second"), array("third", "fourth"));
$arr3 = array(array("fifth", "sixth", "seventh"), array("eighth", "ninth"), array("tenth", "eleventh"));
$arr4=array();
flatten($arr2,$arr4);
flatten($arr3,$arr4);

PHP - Get the value by key in a multi-dimension array

I have a multi-dimension array like:
$fields =
Array (
[1] => Array
(
[field_special_features5_value] => Special Function 5
)
[2] => Array
(
[field_special_features6_value] => Special Function 6
)
[3] => Array
(
[field_opticalzoom_value] => Optical Zoom
)
)
I want to get the value by key, I tried the code below but not work
$tmp = array_search('field_special_features5_value' , $fields);
echo $tmp;
How can I get the value Special Function 5 of the key field_special_features5_value?
Thanks
print $fields[1]['field_special_features5_value'];
or if you don't know at which index your array is, something like this:
function GetKey($key, $search)
{
foreach ($search as $array)
{
if (array_key_exists($key, $array))
{
return $array[$key];
}
}
return false;
}
$tmp = GetKey('field_special_features5_value' , $fields);
echo $tmp;
If you know where it is located in the $fields array, try :
$value = $fields[1]['field_special_features5_value'];
If not, try :
function getSubkey($key,$inArray)
{
for ($fields as $field)
{
$keys = array_keys($field);
if (isset($keys[$key])) return $keys[$key];
}
return NULL;
}
And use it like this :
<?php
$value = getSubkey("field_special_features5_value",$fields);
?>
You need to search recursive:
function array_search_recursive(array $array, $key) {
foreach ($array as $k => $v) {
if (is_array($v)) {
if($found = array_search_recursive($v, $key)){
return $found;
}
} elseif ($k == $key) {
return $v;
} else {
return false;
}
}
}
$result = array_search_recursive($fields, 'field_special_features5_value');
Your problem is that you have a top-level index first before you can search you array. So to access that value you need to do this:
$tmp = $fields[1]['field_special_features5_value'];
You can do it with recursive function like this
<?php
function multi_array_key_exists($needle, $haystack) {
foreach ($haystack as $key=>$value) {
if ($needle===$key) {
return $key;
}
if (is_array($value)) {
if(multi_array_key_exists($needle, $value)) {
return multi_array_key_exists($needle, $value);
}
}
}
return false;
}
?>

Categories