Php string comparision in multidimensional array - php

I have two multidimensional array
Array
(
[0] => Array
(
[code] => 2079
[label] => Nike
)
[1] => Array
(
[code] => 1080
[label] => Adidas
)
)
Array
(
[0] => Array
(
[manufacturers_id] => 2753
[manufacturers_name] => Reebok
)
[1] => Array
(
[manufacturers_id] => 2526
[manufacturers_name] => Adidas
)
[2] => Array
(
[manufacturers_id] => 34
[manufacturers_name] => Nike
)
)
I want to do string matching of a key label of array 1 with key manufacturer_name of array 2. What is the best approach in multidimensional arrays ?

You could loop trough the arrays.
foreach ($multi_array1 as $value) {
foreach ($multi_array2 as $value2) {
If ($value[label] === $value2 [manufacturer_name])
{}
}
}

If you want to match by label and manufacturers_name, then I suggest you reindex your arrays by those fields:
$by_label = [];
foreach($first_array as $element) {
$by_label[$element['label']] = $element['code'];
}
$by_name = [];
foreach($second_array as $element) {
$by_label[$element['manufacturers_name']] = $element['manufacturers_id'];
}
foreach($by_label as $label => $code) {
print "Label is $label, code is $code, id is {$by_name[$label]}";
}
foreach($by_name as $name => $id) {
print "Name is $name, id is $id, label is {$by_label[$name]}";
}

Just use foreach to accomplish your desire result.
Array
$firstArr = array(
array("code" => 2079, "label" => 'Nike'),
array("code" => 1080, "label" => 'Adidas')
);
$secArr = array(
array("manufacturers_id" => 2753, "manufacturers_name" => 'Reebok'),
array("manufacturers_id" => 2526, "manufacturers_name" => 'Adidas'),
array("manufacturers_id" => 34, "manufacturers_name" => 'Nike')
);
Foreach Technique:
foreach($firstArr as $value){
if(in_array_sec($value['label'])){
echo $value['label'].' found in second array.';
}else{
echo $value['label'].' not found in second array.';
}
}
function in_array_sec($val_one){
global $secArr;
$flag = false;
foreach($secArr as $value){
if($value['manufacturers_name'] == $val_one){
$flag = true;
break;
}
else
$flag = false;
}
return $flag;
}
Result:
Nike found in second array.
Adidas found in second array.

Related

Create smart recursive function for multidimensional array which returns all arrays inside in one array

The main thing is multidimensional arrays can be random and I don't know exactly how many arrays inside in it. That why function should include recursion and checks does it have more array inside, example below can't do it without pre configuration. Appreciating any help
$arrays = array(
array(
'House' => 'Baratheon',
'Sigil' => 'A crowned stag',
'Motto' => 'Ours is the Fury',
),
array(
'Leader' => 'Eddard Stark',
'House' => 'Stark',
'Motto' => 'Winter is Coming',
'Sigil' => 'A grey direwolf'
),
array(
array('SomeArray' => 'You are cool'),
'House' => 'Lannister',
'Leader' => 'Tywin Lannister',
'Sigil' => 'A golden lion'
),
array(
'Q' => 'Z'
)
);
function next_element($array) {
foreach ($array as $some_type) {
if (is_array($some_type)) {
return true;
} else {
return false;
}
}
}
function check_in($inputs) {
foreach ($inputs as $position => $input) {
if (is_array($input) && next_element($input)) { // case with multidimentional array
check_in($input);
$check_in_result[] = "There are should be recursion!!!!!";
} else { // case with one simple array
$check_in_result[] = $input;
}
}
return $check_in_result;
}
Have tried with array_walk_recursive() but that function is working with all elements and returns as result one array with all keys and values. In this case it should be array(array1, array2, array3, array4) for next stage which is foreach loop.
As resutl it should be:
Array
(
[0] => Array
(
[House] => Baratheon
[Sigil] => A crowned stag
[Motto] => Ours is the Fury
)
[1] => Array
(
[Leader] => Eddard Stark
[House] => Stark
[Motto] => Winter is Coming
[Sigil] => A grey direwolf
)
[2] => Array
(
[SomeArray] => You are cool
)
[3] => Array
(
[House] => Lannister
[Leader] => Tywin Lannister
[Sigil] => A golden lion
)
[4] => Array
(
[Q] => Z
)
)
Try using a recursive function like this:
function parseMyArray($array) {
$result = [];
$row = [];
foreach($array as $key => $item) {
if (is_array($item)) {
$result = array_merge($result, parseMyArray($item));
} else {
$row[$key] = $item;
}
}
return !empty($row) ? array_merge($result, [$row]) : $result;
}
$result = parseMyArray($arrays);
print_r($result);
At each level of a function call, all scalar values with their keys are collected into one array as $row and merged with the $result of a nested function call.
fiddle

how to get array with unique values in laravel/php

I need to merge arrays into 1 array but what I need is to remove before the main data they b oth have in common (duplicated values i mean), I need only unique values when merged.
array formed from foreach.
public $arrayfields= [];
public $itemMap = [];
public function getRowMapping(array $row,$uniqueField,$moduleName)
{
$arrayData = [];
foreach ($this->columnMapping as $key => $value) {
$row = $this->moduleType($key,$value,$row,$moduleName);
}
$unique = $row[$uniqueField];
if(!isset($this->itemMap[$unique])){
$this->itemMap[$unique] = $row;
$this->itemMap[$unique][$unique]['items'] = [];
}
$this->itemMap[$unique]['items'][] = $row['items'];
return $row;
}
i changed little bit to my input
How can i do that?
so now the input will be like this
Array
(
[bill_type] => 1
[bill_number] => BIL-003
[order_number] => ON-003
[items] => Array
(
[track_inventory] => 0
[sku1] => sku1
[name] => Kidswear1
)
)
Array
(
[bill_type] => 1
[bill_number] => BIL-003
[order_number] => ON-003
[items] => Array
(
[track_inventory] => 0
[sku1] => sku2
[name] => Pant
)
)
Array
(
[bill_type] => 1
[bill_number] => BIL-002
[order_number] => ON-002
[items] => Array
(
[track_inventory] => 0
[sku1] => sku3
[name] => Pants
)
)
The final output I'm looking for is
Array
(
[BIL-003] => Array
(
[bill_type] => 1
[order_number] => ON-003
[items] => Array
(
[0] => Array(
[track_inventory] => 0
[sku1] => sku1
[name] => Kidswear1
)
[1] => Array
(
[track_inventory] => 0
[sku1] => sku2
[name] => Pant
)
)
[BIL-002] => Array
(
[bill_type] => 1
[order_number] => ON-002
[items] => Array
(
[0] => Array(
[track_inventory] => 0
[sku1] => sku3
[name] => pants
)
)
)~~~
I think there is no standard library function to accomplish this.
So here is the function that accomplishes this:
function merge($array1, $array2)
{
$arraymerged = [];
if (is_array($array1) && is_array($array2)) {
//collect the keys of two arrays
$keys = [];
foreach ($array1 as $key => $value) {
$keys[$key] = true;
}
foreach ($array2 as $key => $value) {
$keys[$key] = true;
}
//merge key values for each key
foreach ($keys as $key => $value) {
if (isset($array1[$key]) && isset($array2[$key])) {
if ($array1[$key] == $array2[$key]) {
$arraymerged[$key] = $array1[$key];
} else {
$arraymerged[$key] = [$array1[$key], $array2[$key]];
}
} else if (isset($array1[$key]))
$arraymerged[$key] = $array1[$key];
else
$arraymerged[$key] = $array2[$key];
}
return $arraymerged;
}
}
Here is my suggestion,
if the input is array, check my answer on this post Convert an associative array into an associative array which has a key with another associative array as its value in php
otherwise check below code.
bill_number as unique key and run foreach and append items array elements.
let me give you an example
$arr1 = [
"bill_type" => 1,
"bill_number" => 'BIL-003',
"items"=>[
0 => [
"name"=>"test"
]
]
];
$arr2 = [
"bill_type" => 1,
"bill_number" => 'BIL-003',
"items"=>[
0 => [
"name"=>"test_2"
]
]
];
$formattedArr = [];
//merge these arrays
$combinedArr = [];
$combinedArr[] = $arr1;
$combinedArr[] = $arr2;
foreach($combinedArr as $key=>$value){
$formattedArr[$value['bill_number']]["bill_type"] = $value["bill_type"];
$formattedArr[$value['bill_number']]["items"][] = $value["items"];
}
print_r($formattedArr);
I haven't tested this code, but i think this will be ans to your question.
<?php
$a1 = array(
"bill_type" => "1",
"bill_number" => "BIL-003",
"order_number" => "ON-003",
"items" => array(
"track_inventory" => "0",
"sku1" => "sku1",
"name" => "Kidswear1"
)
);
$a2 = array(
"bill_type" => "1",
"bill_number" => "BIL-003",
"order_number" => "ON-003",
"items" => array(
"track_inventory" => "0",
"sku1" => "sku2",
"name" => "Pant"
)
);
$result = function ($a1, $a2) {
$b1 = $a1['items'];
$b2 = $a2['items'];
$c1 = $a1;
$c2 = $a2;
unset($c1['items']);
unset($c2['items']);
if (count(array_diff($c1, $c2)) == 0) {
if (count(array_diff($b1, $b2)) != 0) {
$c1['items'] = [$b1, $b2];
} else {
$c1['items'] = $b1;
}
return $c1;
}else{
//you should complete this part by yourself, if first parts are not equal.
}
return $c1;
};
$r = $result($a1, $a2);
var_dump($r);
result:
(array) [4 elements]
bill_type: (string) "1"
bill_number: (string) "BIL-003"
order_number: (string) "ON-003"
items:
(array) [2 elements]
0:
(array) [3 elements]
track_inventory: (string) "0"
sku1: (string) "sku1"
name: (string) "Kidswear1"
1:
(array) [3 elements]
track_inventory: (string) "0"
sku1: (string) "sku2"
name: (string) "Pant"

How to read nested array values without knowing the keys?

I'm new in array. I wish to print out the values of all possible [type] [label] [value]. I wish to do like "if there's a type with select, then display all labels with values"
Below is my array.
Array
(
[product_id] => 8928
[title] => Example of a Product
[groups] => Array
(
[8929] => Array
(
[8932] => Array
(
[type] => select
[label] => Section
[id] => pewc_group_8929_8932
[group_id] => 8929
[field_id] => 8932
[value] => Section 200
[flat_rate] => Array
(
)
)
)
)
[price_with_extras] => 0
[products] => Array
(
[field_id] => pewc_group_8929_9028
[child_products] => Array
(
[8945] => Array
(
[child_product_id] => Array
(
[0] => 8945
)
[field_id] => pewc_group_8929_9028
[quantities] => one-only
[allow_none] => 0
)
)
[pewc_parent_product] => 8928
[parent_field_id] => pewc_5d678156d81c6
)
)
The site is saying "
It looks like your post is mostly code; please add some more details." So here's my so-called lorem ipsum :D
You can use array_walk_recursive for the same,
array_walk_recursive($arr, function ($value, $key) {
// check if key matches with type, label or value
if (count(array_intersect([$key], ['type', 'label', 'value'])) > 0) {
echo "[$value] ";
}
});
Demo
Output
[select] [Section] [Section 200]
EDIT
You can modify the condition as,
if($key === 'type' && $value == 'select')
EDIT 1
array_walk_recursive($arr, function ($value, $key) {
if($key === 'type' && $value == 'select'){
echo "[$value] ";
}
});
EDIT 2
function search_by_key_value($arr, $key, $value)
{
$result = [];
if (is_array($arr)) {
if (isset($arr[$key]) && $arr[$key] == $value) {
$result[] = $arr;
}
foreach ($arr as $value1) {
$result = array_merge($result, search_by_key_value($value1, $key, $value));
}
}
return $result;
}
// find array by key = type and value = select
$temp = search_by_key_value($arr, 'type', 'select');
$temp = array_shift($temp);
print_r($temp);
echo $temp['label'];
echo $temp['value'];
Demo

How to get difference between Associate arrays in PHP

I have an arrays like this
Array
(
[original_data] => Array
(
[0] => Array
(
[reference_id] => 122
[id] => 121
[reference_name] => Dinesh
)
[1] => Array
(
[reference_id] => 123
[id] => 120
[reference_name] => Dinesh Test
)
)
[edited_data] => Array
(
[0] => Array
(
[reference_id] => 123
[id] => 120
[reference_name] => Dinesh Test2
)
)
)
I want to get the difference between this original_data and edited_data arrays. How to do that? I tried using array_diff. But, It didn't work correctly.
You can get the difference =>
$result = ref_array_diff($requestedData['edited_data'], $requestedData['data']);
print_r($result);
function ref_array_diff($arraya, $arrayb) {
foreach ($arraya as $keya => $valuea) {
if (in_array($valuea, $arrayb)) {
unset($arraya[$keya]);
}
}
return $arraya;
}
If you use array_map on both original data and edited data to get an array of original_data id values and edited_data id values. You can then use array_diff with no problem. Using the resulting list of id's which are in one but not the other you can lookup the original value using the array mapped values index key on the original arrays.
I'm making the assumption here that your id key is a unique identifier for each value in the data arrays. If this isn't the case you'll need to do some nested loops to compare deep values
This should work.
<?php
// your data
$data = array (
'original_data' => array
('0' => array
(
'reference_id' => 122,
'id' => 121,
'reference_name' => 'Balasuresh,'
),
'1' => array
(
'reference_id' => 123,
'id' => 120,
'reference_name' => 'Balasuresh',
),
),
'edited_data' => array
('0' => array
(
'reference_id' => 123,
'id' => 120,
'reference_name' => 'Balasuresh Test',
),
)
) ;
// let's get our reference_ids
$originalData = array() ;
foreach($data['original_data'] as $entry) {
$originalData[$entry['reference_id']] = $entry ;
}
// let's compare our edited data to our original data
$editedData = array() ;
foreach($data['edited_data'] as $editedEntry) {
if (isset($originalData[$editedEntry['reference_id']])) {
// for readability
$compare = $originalData[$editedEntry['reference_id']] ;
foreach($editedEntry as $key=>$value) {
if ($compare[$key] != $value) {
$editedData[$editedEntry['reference_id']][$key] = $value ;
}
}
}
}
$editedData now contains your differences
These are multi-dimensional associative arrays, you can recursively do an array_diff_assoc like this:
you can check this code here https://3v4l.org/ovaQB:
function array_diff_assoc_recursive($array1, $array2)
{
foreach($array1 as $key => $value)
{
if(is_array($value))
{
if(!isset($array2[$key]))
{
$difference[$key] = $value;
}
elseif(!is_array($array2[$key]))
{
$difference[$key] = $value;
}
else
{
$new_diff = array_diff_assoc_recursive($value, $array2[$key]);
if($new_diff != FALSE)
{
$difference[$key] = $new_diff;
}
}
}
elseif(!isset($array2[$key]) || $array2[$key] != $value)
{
$difference[$key] = $value;
}
}
return !isset($difference) ? 0 : $difference;
}
$a=["original_data"=>[
[
'reference_id' => 122,
'id' => 121,
'reference_name' => 'Balasuresh'
],[
'reference_id' => 123,
'id' => 120,
'reference_name' => 'Balasuresh'
]
],
'edited_data' => [[
'reference_id' => 123,
'id' => 120,
'reference_name' => 'Balasuresh Test'
]]
];
print_r(array_diff_assoc_recursive($a['edited_data'], $a['original_data']));
output:
Array
(
[0] => Array
(
[reference_id] => 123
[id] => 120
[reference_name] => Balasuresh Test
)
)

2 arrays match data into 1 array with PHP

I have 2 array's, first array have for example ItemID of my item, second array have description about my item. I want to match data into 1 array.
It looks like:
[rgInventory] => Array
(
[1234567890] => Array
(
[id] => 1234567890
[classid] => 123456789
[instanceid] => 987654321
[amount] => 1
[pos] => 1
)
)
[rgDescriptions] => Array
(
[192837465_918273645] => Array
(
[appid] => 730
[name] => Something
)
)
Items in arrays don't have the same value like ID, but they are in the same order so:
Description for the first item in rgInventory is in the first array inside rgDescriptions.
What should I do to match for example id from rgInventory with name from rgDescriptions in the same array for example $backpack = array();?
Regards for you.
Try this:
<?php
$array1 = array('rgInventory' =>
array(
'1234567890' => array(
'id' => 1234567890,
'classid' => 123456789,
'instanceid' => 987654321,
'amount' => 1,
'pos' => 1
)
)
);
$array2 = array(
'rgDescriptions' => array(
'192837465_918273645' => array(
'appid' => 730, 'name' => 'Something')
)
);
Create new function to combine the two arrays into one array:
function array_sum_recursive($data1, $data2) {
if (!is_array($data1) && !is_array($data2)) {
return $data1 + $data2;
}
// deepest array gets precedence
if (!is_array($data2)) {
return $data1;
}
if (!is_array($data1)) {
return $data2;
}
//merge and remove duplicates
$keys = array_unique(array_merge(array_keys($data1), array_keys($data2)));
foreach ($keys as $key) {
if (isset($data1[$key]) && isset($data2[$key])) {
$result[$key] = array_sum_recursive($data1[$key], $data2[$key]);
} else if (isset($data1[$key])) {
$result[$key] = $data1[$key];
} else {
$result[$key] = $data2[$key];
}
}
if(empty($result)){
echo "no result";
die();
}else{
return $result;
}
}
Put the two array in one array $newarray:
$newonearray = array_sum_recursive($array1, $array2);
echo '<pre>';
print_r($newonearray);
?>
And you will get this:
Array
(
[rgInventory] => Array
(
[1234567890] => Array
(
[id] => 1234567890
[classid] => 123456789
[instanceid] => 987654321
[amount] => 1
[pos] => 1
)
)
[rgDescriptions] => Array
(
[192837465_918273645] => Array
(
[appid] => 730
[name] => Something
)
)
)
Hope this may help.
You can use function each to get each element of both arrays, then merge its with array_merge and save this new item to backup array.
Try something like this
<?php
$rgInventory = ['firstInv' => ['invId' => 1], 'secondInv' => ['invId' => 2]];
$rgDescriptions = ['firstDesc' => ['descId' => 1], 'secondDesc' => ['descId' => 2]];
if (count($rgInventory) && count($rgInventory) == count($rgDescriptions)) {
$backpack = [];
while($inventory = each($rgInventory)) {
$description = each($rgDescriptions);
$item = array_merge($inventory['value'], $description['value']);
$backpack[] = $item;
}
var_dump($backpack);
}
Output will be:
array(2) {
[0]=>
array(2) {
["invId"]=>
int(1)
["descId"]=>
int(1)
}
[1]=>
array(2) {
["invId"]=>
int(2)
["descId"]=>
int(2)
}
}

Categories