I have this array:
ARRAY 1
Array
(
[0] => Array
(
[required] => Tip:
)
[1] => Array
(
[required] => Flux:
)
[2] => Array
)
ARRAY 2
Array
(
[0] => Array
(
[name] => Flux:
)
[1] => Array
(
[name] => Tip:
)
[2] => Array
(
[name] => Weight:
)
)
How insert data from array 1 to array 2 when value of name and required are same. Data from array some time don't have same values of name and required. On output of array 2 I want to display something when value of required exist.
I need this:
Array
(
[0] => Array
(
[name] => Flux:
[required] => Flux:
)
[1] => Array
(
[name] => Tip:
[required] => Tip:
)
[2] => Array
(
[name] => Weight:
[required] =>
)
)
I tried with this:
foreach($char as $key =>$value){
foreach($mandatory as $key =>$val){
$data[] = array("name" => $value->charact_name, "required" => $val);
}
}
But is not output what I expect! It show me diferent values on name and required
CodePudding user response:
This question is not a technical problem and you needed a little more tries to achieve a true algorithm.
I did some modifications to your code. $key
variable must be different for two foreach
s. Based on your question new key required
just added to $arr2
.
$arr1 = [['required' => 'Tip:'], ['required' => 'Flux:']];
$arr2 = [['name' => 'Flux:'], ['name' => 'Tip:'], ['name' => 'Weight:']];
foreach($arr2 as $key2 => $value2) {
$arr2[$key2]['required'] = NULL;
foreach($arr1 as $value1)
if($value2['name'] == $value1['required']) {
$arr2[$key2]['required'] = $value1['required'];
break;
}
}
CodePudding user response:
I tried this:
foreach($char as $key2 => $value2) {
foreach($mandatory as $value1)
if($value2->charact_name == $value1) {
$data[] = array("name" => $value2->charact_name, "required" => $value1);
}
}
But data array it show me name and required only for values that is in $mandatory
array, I want to display all from $char
and when value exist in $mandatory add [required]=> name
of value from $mandatory
CodePudding user response:
You can simply create it with nested loops which cause time complexity O(n*m). However if you use a Hashmap (array with key value) which get O(1) to search you can create it very fast by O(n m) as below:
<?php
$arr1 = array(0 => array('name' => 'Flux'),1 => array('name' => 'Tip'),2 => array('name' => 'Weight'));
$arr2 = array(0 => array('required' => 'Tip'),1 => array('required' => 'Flux'),2 => array());
$arrkey = array();
foreach ($arr1 as $ix=>$value) {
$arrkey[$value['name']]=$ix;
}
$arr3 = $arr1;
foreach ($arr2 as $elem) {
if(!empty($elem) && array_key_exists($elem['required'],$arrkey)) {
$arr3[$arrkey[$elem['required']]]['required'] = $elem['required'];
}
}
print_r($arr3);
?>
Try this online demo.