I have 2 different multidimensional array that are structured in the following way
ARRAY 1
Array
(
[0] => Array
(
[0] => john
[1] => AUTHOR
[2] => PUBLISHER
)
[0] => Array
(
[0] => Smith
[1] => AUTHOR
[2] => PUBLISHER
)
)
ARRAY 2
Array
(
[0] => Array
(
[0] => John
[1] => www.john.com
[2] => D
)
[1] => Array
(
[0] => Smith
[1] => smith.com
[2] => D
)
)
I would like two check if the value "john" from Array1 is available in array2. If it's the case, i retrieve the value of "www.john.com" in array2 and insert it in array 1
This is what i would like to achieve
FINAL ARRAY
ARRAY 1
Array
(
[0] => Array
(
[0] => john
[1] => www.john.com
[2] => AUTHOR
[3] => PUBLISHER
)
[0] => Array
(
[0] => Paul
[1] => AUTHOR
[2] => PUBLISHER
)
)
The array is dynamic, i put static values just to show what i would like to acheive.
Any help on this will be appreciated
This will work for you, but see comment below:
$arrayFirst = array(
arraey('John', 'AUTHOR', 'PUBLISHER',),
array('Smith', 'AUTHOR', 'PUBLISHER')) ;
$arraySecond = array(
array('John', 'www.john.com', 'D'),
array('Smith', 'smith.com', 'D'));
foreach ($arrayFirst as $kye => $subArrayFirst){
foreach ($arraySecond as $subArraySecond){
if(in_array($subArrayFirst[0], $subArraySecond)) {
$arrayFirst[$kye][] = $subArraySecond[1];
}
}
}
var_dump($arrayFirst);
But in this case it is important the position of authow name and address
$s1 = [
['John', 'AUTHOR', 'PUBLISHER'],
['Smith', 'AUTHOR', 'PUBLISHER']
];
$s2 = [
['John', 'www.john.com', 'D'],
['Smith', 'smith.com', 'D']
];
foreach ($s1 as &$info) {
$name = $info[0];
foreach ($s2 as $info2) {
if (in_array($name, $info2)) {
$url = $info2[1];
$info[] = $url;
}
}
This is a simple and fast way.
for($i=0;i<=Array1.length;i++){
for($j=0;j<=Array2.length;j++){
if (Array1[0][0] == Array2[i][j]){
echo Array2[i][j];
Array1[0][1] = Array2[i][j];
break;
break;
}
}
}
I hope that helps
You can write a function which checks if one item from array1 is avaiable in array2:
function arrayTwoContains($element)
{
foreach($array2 as $elemFrom2)
{
if(strtolower($element[0])==strtolower($elemFrom2[0])) //if the names from array1 and array 2 are equal: return element two
{
return $elemFrom2;
}
}
return false;
}
Then you can build a loop where you run through array1 and if arrayTwoContains() returns not false, you put the values in a new array.
$fused = array(); // your new array
$key = 0; //current index of new array
foreach($array1 as $element)
{
if($elemFromTwo = arrayTwoContains($element))
{
$elementToInsert = array();
$elementToInsert[0] = $element[0];
$elementToInsert[1] = $elemFromTwo[1];
$elementToInsert[2] = $element[1];
$elementToInsert[3] = $element[2];
$fused[$key] = $elementToInsert;
$key++;
}
}
I hope this works, I haven't done anything in PHP since months ;)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.