Reputation: 13
I have to add some elements from an array into another array for a project.
Here's the deal: I have 2 arrays, from 2 tables of a database, which are named $stand
and $signal
.
$stand
is made up of arrays:
$stand = [[id, name, width, length,...], [id, name, width, length,...], ...]
$signal
is made up of arrays as well:
$signal = [[id, num, name, adress, ...], [id, num, name, adress, ...], ...]
Each entry of $stand
matches with an entry of $signal
: the id of an entry of $stand
is equal to the number of elements in $signal
.
For these entries, I'd like to add the content of the entry of $signal
at the end of the entry of $stand
.
Here's the code I used, but unfortunately it doesn't work:
foreach ($stand as $st) {
foreach ($signal as $sig) {
if ($st[0] == $sig[1]) {
$st[]=$sig;
}
}
}
Upvotes: 1
Views: 548
Reputation: 785
foreach ($stand as $key => $st) {
foreach ($signal as $sig) {
if ($st[0] == $sig[1]) {
$stand[$key][]=$sig;
}
}
}
Upvotes: 1
Reputation: 5437
As I understand, you want something like this
$array1 = array(array('id'=>1,'name'=>'manish'),array('id'=>2,'name'=>'bhuvnesh'));
$array2 = array(array('id'=>1,'color'=>'red'),array('id'=>2,'color'=>'green'));
$newArray = array();
foreach($array1 as $key => $vals) {
$id = $vals['id'];
$color = $array2[$key]['color'];
$newArray[] = array('id'=>$id, 'name'=>$vals['name'], 'color'=>$color);
}
echo '<pre>';
print_r($newArray);
This will return
Array
(
[0] => Array
(
[id] => 1
[name] => manish
[color] => red
)
[1] => Array
(
[id] => 2
[name] => bhuvnesh
[color] => green
)
)
Upvotes: 0
Reputation: 2377
Use array_merge function.
$array1 = array("color" => "red", 2, 4);
$array2 = array("a", "b", "color" => "green", "shape" => "trapezoid", 4);
$result = array_merge($array1, $array2);
print_r($result);
For more detail read here
Upvotes: 2
Reputation:
$st seems to be a copy of an element array, but not an element reference. So modifications you make to $st are lost. Thus you should precede $st with an ampersand to use it as a reference:
foreach($stand as &$st)
Upvotes: 0
Reputation: 1681
array_merge is the elegant way:
$a = array('a', 'b');
$b = array('c', 'd');
$merge = array_merge($a, $b);
// $merge is now equals to array('a','b','c','d');
Doing something like:
$merge = $a + $b;
// $merge now equals array('a','b')
Will not work, because the + operator does not actually merge them. If they $a has the same keys as $b, it won't do anything.
Upvotes: 8