php multidimensional array key value search from two different arrays - php

I have two different array. The array are like
first array is like
Array
(
[0] => Array
(
[source_language] => English
[target_language] => Array
(
[0] => German
[1] => Norwegian
)
[title] => file 1.xlsx
[file_name] => 1461911750_file_test.xlsx
)
[1] => Array
(
[source_language] => Hindi
[target_language] => Array
(
[0] => Belarusian
)
[title] => new files.xlsx
[file_name] => 1461912206_file_here_files.xlsx
)
)
Second array is like
Array
(
[1] => Array
(
[source_language] => English
[target_language] => Array
(
[0] => Urdu
[1] => Hindi
)
)
[2] => Array
(
[source_language] => Hindi
[target_language] => Array
(
[0] => Norwegian
)
)
[3] => Array
(
[source_language] => Hindi
[target_language] => Array
(
[0] => German
)
)
[3] => Array
(
[source_language] => English
[target_language] => Array
(
[0] => German
[1] => Norwegian
)
)
)
Now you can both array same key for source_langauge and target_language . The title and file_name key is available only in first array
So I want that the first array will search all the source_language and target_language from the second array and show both matching arrays and non matching arrays
So the output should be like this
The matching array is
[0] => Array
(
[source_language] => English
[target_language] => Array
(
[0] => German
[1] => Norwegian
)
[title] => file 1.xlsx
[file_name] => 1461911750_file_test.xlsx
)
as it has same values source language and target language in second array
The other result will show is
non matching array is
[0] => Array
(
[source_language] => Hindi
[target_language] => Array
(
[0] => Belarusian
)
[title] => new files.xlsx
[file_name] => 1461912206_file_here_files.xlsx
)
as this source language and target languages are not found in second array.
Update
I have tried so far is
$diffs = [];
foreach ($first_array as $a1) {
$h1 = md5(json_encode($a1));
$found = false;
foreach ($second_array as $a2) {
if (md5(json_encode($a2)) == $h1) {
$found = true;
break;
}
}
if ( !$found ) {
$diffs []= $a1;
}
}
But this one is not working at all

First off, you can't compare $h1 to $a2 since they don't share the exact same structure.
$h1 still has that title and filename key pair values.
No need to use md5 and json_encode, since you just need to compare two string values:
$match = $no_match = array();
foreach($first as $f) {
$found = false;
foreach($second as $s) {
if(
$f['source_language'] === $s['source_language'] &&
$f['target_language'] === $s['target_language']
) {
$match[] = $f;
$found = true;
}
}
if(!$found) {
$no_match[] = $f;
}
}

<?php
$arr1 = array();
$arr2 = array();
$arr1[0] = array('source_language'=>'English','target_language'=>array('German','Norwegian'),'title'=>'file 1.xlsx','file_name'=>'1461911750_file_test.xlsx');
$arr1[1] = array('source_language'=>'Hindi','target_language'=>array('Belarusian'),'title'=>'new files.xlsx','file_name'=>'1461912206_file_here_files.xlsx');
$arr2[0] = array('source_language'=>'English','target_language'=>array('Urdu','Hindi'));
$arr2[1] = array('source_language'=>'Hindi','target_language'=>array('Norwegian'));
$arr2[2] = array('source_language'=>'Hindi','target_language'=>array('German'));
$arr2[3] = array('source_language'=>'English','target_language'=>array('German','Norwegian'));
$result_arr = array();
for($i=0;$i<count($arr2);$i++)
{
for($j=0;$j<count($arr1);$j++)
{
if(($arr2[$i]['source_language'] === $arr1[$j]['source_language']) && ($arr2[$i]['target_language'] === $arr1[$j]['target_language']))
$result_arr[] = $arr1[$j];
}
}
print_r(json_encode($result_arr));
?>

The solution using array_walk and array_diff functions:
$matched = $not_matched = [];
array_walk($array1, function($v) use($array2, &$matched, &$not_matched){
foreach ($array2 as $item) {
if ($v['source_language'] == $item['source_language']
&& empty(array_diff($v['target_language'], $item['target_language']))) {
$matched[] = $v;
break;
}
}
if (!in_array($v, $matched)) $not_matched[] = $v;
});
echo "Matched items:". PHP_EOL;
print_r($matched);
echo "Not-matched items:". PHP_EOL;
print_r($not_matched);
The output:
Matched items:
Array
(
[0] => Array
(
[source_language] => English
[target_language] => Array
(
[0] => German
[1] => Norwegian
)
[title] => file 1.xlsx
[file_name] => 1461911750_file_test.xlsx
)
)
Not-matched items:
Array
(
[0] => Array
(
[source_language] => Hindi
[target_language] => Array
(
[0] => Belarusian
)
[title] => files.xlsx
[file_name] => 1461912206_file_here_files.xlsx
)
)

Related

Convert Complex array to simple one (for CSV)

I want to convert my complex array to simpler one for exporting that converted simpler array to the CSV file.
Currently my array structure is like:
Array
(
[0] => Array
(
[_source] => Array
(
[block] => Array
(
[0] => Kurud
)
[district] => Array
(
[0] => Dhamtari
)
[state] => Array
(
[0] => Chhattisgarh
)
)
)
[1] => Array
(
[_source] => Array
(
[block] => Array
(
[0] => North-Bangeluru
)
[district] => Array
(
[0] => Bangalore
)
[state] => Array
(
[0] => Karnataka
)
)
)
)
and I want to convert above array to the below given format:
array(
array("block", "district", "state"),
array("Kurud","Dhamtari","Chhattisgarh"),
array("North-Bangeluru","Bangalore","Karnataka")
)
So keys will be the first element and then each element with his data.
This is what I tried:
foreach ($array as $key => $value) {
if (is_array($value)) {
$result = array_merge($result);
}
else {
$result[$key] = $value;
}
}
print_r(result);
thanks in advance...
How about:
$keys = array_keys($arr[0]["_source"]);
$res[] = $keys;
foreach($arr as $e) {
$temp = [];
foreach($keys as $k)
$temp[] = $e["_source"][$k][0];
$res[] = $temp;
}
Reference: array-keys
Live example: 3v4l

Change value inside an array

I'd like to change the values of an array.
Currently my array looks like this:
Array
(
[0] => Array
(
[0] => 12-Multi_select-customfield-retina-ready+Yes
[1] => 12-Multi_select-customfield-retina-ready+N/A
[2] => 12-Multi_select-customfield-retina-ready+No
)
)
I want to remove everything before the + symbol, so in the end the new array will looke like this
Array
(
[0] => Array
(
[0] => Yes
[1] => N/A
[2] => No
)
)
This is my code:
$new_array = array();
foreach( $array as $key => $value ) {
$split = explode("+", $value[0]);
$new_array[] = $split[1];
}
Hoping that it would worked, but when I check the new array, it only shows one value.
Array
(
[0] => Yes
)
Any help in putting me in the right direction is much appreciated.
Please, check it:
<?php
$array[0][0] = '12-Multi_select-customfield-retina-ready+Yes';
$array[0][1] = '12-Multi_select-customfield-retina-ready+N/A';
$array[0][2] = '112-Multi_select-customfield-retina-ready+No';
echo '<pre>';
print_r($array);
$new_array = array();
foreach( $array[0] as $key => $value ) {
$split = explode("+", $value);
$new_array[] = $split[1];
}
print_r($new_array);
echo '</pre>';
Try This this work even if you have multiple key in the original array $original_array[0], $original_array[1] ... :
$original_array[0] = [
0 => '12-Multi_select-customfield-retina-ready+Yes',
1 => '12-Multi_select-customfield-retina-ready+N/A',
2 => '12-Multi_select-customfield-retina-ready+No'
];
print_r($original_array);
$new_array = [];
foreach ($original_array as $key => $value) {
foreach ($value as $index => $val) {
$split = explode("+", $val);
$new_array[$key][] = $split[1];
}
}
print_r($new_array);
Example :
Original array
Array
(
[0] => Array
(
[0] => 12-Multi_select-customfield-retina-ready+Yes
[1] => 12-Multi_select-customfield-retina-ready+N/A
[2] => 12-Multi_select-customfield-retina-ready+No
),
[1] => Array
(
[0] => 12-Multi_select-customfield-retina-ready+Yes
[1] => 12-Multi_select-customfield-retina-ready+N/A
[2] => 12-Multi_select-customfield-retina-ready+No
)
)
New Array
Array
(
[0] => Array
(
[0] => Yes
[1] => N/A
[2] => No
),
[1] => Array
(
[0] => Yes
[1] => N/A
[2] => No
)
)

How to concatenate arrays element recursively [duplicate]

This question already has answers here:
Joining similar data from two indexed arrays
(2 answers)
Closed 5 months ago.
I'm working on a project and I'm stacked since 2 days, this is my problem: I have two arrays and want to retrieve the second item in each object in Array_2 and concatenate it to the content of each object in first Array_1 in PHP.
Array_1
[[1453274700000,24011],[1453275000000,24222],[1453275300000,24284],[1453275600000,24331],...]
Array_2
[[1453274700000,51951],[1453275000000,52093],[1453275300000,52251],[1453275600000,52288],...]
Wanted_array
[[1453274700000,24011,51951],[1453275000000,24222,52093],[1453275300000,24284,52251],[1453275600000,24331,52288]...]
A functional solution:
$result = array_map(function (array $a1, array $a2) {
return array_merge($a1, [$a2[1]]);
}, $array_1, $array_2);
This assumes that all items are in order and only need to be merged by their order, not by their first value.
If you want $item[0] to define what "group" each value belongs to, you can iterate through the first array and save $item[0] as the key and $item[1] as the value. Do the same for the second array. Now iterate through the saved array for array1, and check if the saved array for array2 contains the same keys. Do the same for array2 (in case it has key that array1 doesn't have), and save it all to a new array:
<?php
$arr1 = array(
array('1453274700000',24011),
array('1453275000000',24222),
array('1453276000000',24222), // inexistent in $arr2
);
$arr2 = array(
array('1453275000000',52093),
array('1453274700000',51951),
array('1453273000000',24222), // inexistent in $arr1
);
$arr1dictionary = [];
$arr2dictionary = [];
$result = [];
foreach ($arr1 as $collection) {
$arr1dictionary[$collection[0]] = $collection[1];
}
foreach ($arr2 as $collection) {
$arr2dictionary[$collection[0]] = $collection[1];
}
foreach ($arr1dictionary as $key => $value) {
if (isset($arr2dictionary[$key])) {
$result[$key] = [$key, $value, $arr2dictionary[$key]];
} else {
$result[$key] = [$key, $value, null];
}
}
foreach ($arr2dictionary as $key => $value) {
if (isset($result[$key])) {
continue;
}
$result[$key] = [$key, null, $value];
}
$result = array_values($result);
print_r($result);
Output:
Array
(
[0] => Array
(
[0] => 1453274700000
[1] => 24011
[2] => 51951
)
[1] => Array
(
[0] => 1453275000000
[1] => 24222
[2] => 52093
)
[2] => Array
(
[0] => 1453276000000
[1] => 24222
[2] => (null, the value only exists in $arr1)
)
[3] => Array
(
[0] => 1453273000000
[1] => (null, the value only exists in $arr2)
[2] => 24222
)
)
DEMO
Use array_walk and add second item from $array2 if it exists.
$array1 = array(
array(1453274700000,24011),
array(1453275000000,24222),
array(1453275300000,24284),
array(1453275600000,24331)
);
$array2 = array(
array(1453274700000,51951),
array(1453275000000,52093),
array(1453275300000,52251),
array(1453275600000,52288),
);
array_walk($array1, function(&$item, $key) use ($array2){
if(isset($array2[$key][1])){
$item[] = $array2[$key][1];
}
});
print_r($array1);
Output
Array
(
[0] => Array
(
[0] => 1453274700000
[1] => 24011
[2] => 51951
)
[1] => Array
(
[0] => 1453275000000
[1] => 24222
[2] => 52093
)
[2] => Array
(
[0] => 1453275300000
[1] => 24284
[2] => 52251
)
[3] => Array
(
[0] => 1453275600000
[1] => 24331
[2] => 52288
)
)
EDIT
As #h2ooooooo pointed out that there could be possibility that array items are in random order. If array items can be in random order and they are matched with first index value, use this (works with PHP >= 5.5.0):
$array1 = array(
array(1453274700000,24011),
array(1453275000000,24222),
array(1453275300000,24284),
array(1453275600000,24331),
array(1453276000000,24222) // no match in $array2
);
$array2 = array(
array(1453275000000,52093),
array(1453274700000,51951),
array(1453275300000,52251),
array(1453275600000,52288),
);
array_walk($array1, function(&$item, $key) use ($array2){
// Find match in $array2
$array2_key = array_search($item[0], array_column($array2, 0));
// If match found
if($array2_key !== false && isset($array2[$array2_key][1])){
$item[] = $array2[$array2_key][1];
}
// No match
else{
$item[] = null;
}
});
print_r($array1);
OUTPUT
Array
(
[0] => Array
(
[0] => 1453274700000
[1] => 24011
[2] => 51951
)
[1] => Array
(
[0] => 1453275000000
[1] => 24222
[2] => 52093
)
[2] => Array
(
[0] => 1453275300000
[1] => 24284
[2] => 52251
)
[3] => Array
(
[0] => 1453275600000
[1] => 24331
[2] => 52288
)
[4] => Array
(
[0] => 1453276000000
[1] => 24222
[2] =>
)
)

How to parse this simple text-block into a multi-dimensional array, in PHP?

I have a simple text-block; and, its content is:
txt_1(val_1,val_2,val_3).
txt_1(val_4,val_5,val_6).
txt_2(val_7,val_8,val_9).
txt_3(val_10,val_11,val_12).
txt_3(val_13,val_14,val_15).
txt_4(val_16,val_17,val_18).
And, there is already an simple array, in PHP code:
$my_array = array();
Now, I want to parse into this PHP array, like:
Array
(
[txt_1] => Array
(
[0] => Array
(
[0] => val_1
[1] => val_2
[2] => val_3
)
[1] => Array
(
[0] => val_4
[1] => val_5
[2] => val_6
)
)
[txt_2] => Array
(
[0] => Array
(
[0] => val_7
[1] => val_8
[2] => val_9
)
)
[txt_3] => Array
(
[0] => Array
(
[0] => val_10
[1] => val_11
[2] => val_12
)
[1] => Array
(
[0] => val_13
[1] => val_14
[2] => val_15
)
)
[txt_4] => Array
(
[0] => Array
(
[0] => val_16
[1] => val_17
[2] => val_18
)
)
)
All data is general. Could you help me to do it, with PHP?
<?php
// Initially put your input into a variable
$txt=<<<__EOT__
txt_1(val_1,val_2,val_3).
txt_2(val_4,val_5,val_6).
txt_n(val_a,val_b,val_c).
__EOT__;
$result = array();
// separate out each row
$rows = explode("\n", $txt);
// loop through each row
foreach($rows as $row) {
// Use a regular expression to find the key and values
$success = preg_match('/^([^(]+)\(([^)]+)\)\.$/', $row, $parts);
// Check the regexp worked
if(!$success) {
echo 'Failed to match row: ' . $row . "\n";
continue;
}
// get the array key from the regexp results
$key = $parts[1];
// the values are all a string, split on the comma to make an array
$values = explode(',', $parts[2]);
// store $key and $values in the result
$result[$key] = $values;
}
// See if it worked
var_dump($result);
Suppose this answer will help you
$text = "
txt_1(val_1,val_2,val_3).
txt_2(val_4,val_5,val_6).
txt_3(val_a,val_b,val_c).
";
$myArry = explode(".", $text);
$resArry = array();
foreach ($myArry as $key => $value) {
if(trim($value)!=""){
$plain = str_replace(array("(",")"),",",$value);
$subArry = explode(",",$plain);
$keyN = explode("(",trim($value));
unset($subArry[array_search($keyN[0],$subArry)]);
unset($subArry[array_search("",$subArry)]);
$resArry[$keyN[0]][]=$subArry;
}
}
echo "<pre/>";
print_r($resArry);
die;
//Output will be like
Array
(
[txt_1] => Array
(
[0] => Array
(
[1] => val_1
[2] => val_2
[3] => val_3
)
)
[txt_2] => Array
(
[0] => Array
(
[1] => val_4
[2] => val_5
[3] => val_6
)
)
[txt_3] => Array
(
[0] => Array
(
[1] => val_a
[2] => val_b
[3] => val_c
)
)
)
$input = 'txt_1(val_1,val_2,val_3).
txt_1(val_4,val_5,val_6).
txt_2(val_7,val_8,val_9).
txt_3(val_10,val_11,val_12).
txt_3(val_13,val_14,val_15).
txt_4(val_16,val_17,val_18).'; // the input string
$temp = explode('.', $input); // seprates from .
$temp = array_filter($temp); // for cutting blank values
$temp = array_map('trim', $temp); // removes newlines
$final = [];
foreach($temp as $val)
{
$key = strtok($val, '('); // search upto token (
$final[$key][] = explode(',' ,strtok(')')); // advance token to )
}
unset($val, $temp); // unset non required things
Here is the output for $final,
Array
(
[txt_1] => Array
(
[0] => Array
(
[0] => val_1
[1] => val_2
[2] => val_3
)
[1] => Array
(
[0] => val_4
[1] => val_5
[2] => val_6
)
)
[txt_2] => Array
(
[0] => Array
(
[0] => val_7
[1] => val_8
[2] => val_9
)
)
[txt_3] => Array
(
[0] => Array
(
[0] => val_10
[1] => val_11
[2] => val_12
)
[1] => Array
(
[0] => val_13
[1] => val_14
[2] => val_15
)
)
[txt_4] => Array
(
[0] => Array
(
[0] => val_16
[1] => val_17
[2] => val_18
)
)
)
Test it here: http://phptester.net/
NOTE: In order to use the short array syntax [] use PHP 5.4
<?php
$text = "
txt_1(val_1,val_2,val_3).
txt_2(val_4,val_5,val_6).
txt_n(val_a,val_b,val_c).
";
$myArray = [];
//You're gonna see why we want to remove this character
//later, it will help us have a cleaner code.
$text = str_replace(')', '', $text);
$arrayGroup = explode('.', $text);
//print_r($arrayGroup);
foreach($arrayGroup as $array) {
$exp = explode('(', $array);
$arrayName = trim($exp[0]);
$arrayValues = explode(',', $exp[1]);
foreach($arrayValues as $value) {
${$arrayName}[] = $value;
}
$myArray[$arrayName] = $$arrayName;
}
echo '<pre>';
print_r($myArray);
echo '</pre>';
echo '<pre>';
print_r($myArray['txt_2']);
echo '</pre>';
After all this, you can use the txt_1 or txt_2 or whatever later, because the variables were created dynamically.
Later in the code you can use $myVar = txt_1[3]; with no problem

Recursive PHP Tree (permutations)

I'm looking to write a function which creates all permutation of a list of arrays (The list is dynamical). Now I found 2 articles, http://dannyherran.com/2011/06/finding-unique-array-combinations-with-php-permutations/ and Finding cartesian product with PHP associative arrays. But I don't want to store them as multiple arrays, I want to add each array to each possibility so I can use them later.
In fact I want to multiply each array with the other.
For example:
$array = array(
array(
1,
2
),
array(
'A',
'B',
'C'),
array(
'I',
'II')
);
In this form:
Array
(
[0] => Array
(
[0] => 1
[1] => Array
(
[0] => Array
(
[0] => A
[1] => Array
(
[0] => I
[1] => II
)
)
[1] => Array
(
[0] => B
[1] => Array
(
[0] => I
[1] => II
)
)
[2] => Array
(
[0] => C
[1] => Array
(
[0] => I
[1] => II
)
)
)
)
[1] => Array
(
[0] => 2
[1] => Array
(
[0] => Array
(
[0] => A
[1] => Array
(
[0] => I
[1] => II
)
)
[1] => Array
(
[0] => B
[1] => Array
(
[0] => I
[1] => II
)
)
[2] => Array
(
[0] => C
[1] => Array
(
[0] => I
[1] => II
)
)
)
)
)
I think this big example made my problem clear. For this type of array I created a function:
foreach ($array[1] as $value) {
$return1[] = array($value, $array[2]);
}
foreach ($array[0] as $value) {
$return[] = array($value, $return1);
}
print_r($return);
Now I want to create this function inside a recursive function (so it becomes dynamical) but I got stuck. I wanted to pass the amount of arrays to the function and then iterate.
function createTree($array, $loops=3){
$b = $array[$loops-2];
foreach ($b as $v) {
$return[] = array($v, createTree($return, $loops-1));
}
print_r($return);
}
Maybe there is a total other solution to multiply the arrays? But the function which isn't recursive is easy for me, but making it recursive...
Thanks for your help
function createTree($array){
switch(count($array)) {
case 0:
die('Illegal argument.');
case 1:
return $array[0];
default:
$lastArray = array_pop($array);
$subArray = createTree($array);
foreach ($lastArray as $item) {
$return[] = array($item, $subArray);
}
return $return;
}
}
var_dump(createTree(array_reverse($array)));

Categories