Php merge arrays [duplicate]
So I have these two foreach
foreach($find as $e) {
$theData[] = array('href' => $e->href, 'linkText' => $e->plaintext);
foreach($findText as $f){
$theData[] = array('description' => $f->plaintext);
}
}
So I need that the result to be something like this: $theData = array('href' => $e->href, 'linkText' => $e->plaintext,'description' => $f->plaintext);
array_merge
doesn't do want I want to achive.Any help?
Try...
$i = 0;
foreach($find as $e){
$data[$i] = array('href' => $e->href, 'linkText' => $e->plaintext);
foreach($findText as $f){
$data[$i]["description"][] = $f->plaintext;
}
$i++;
}
If your arrays both have automatically created integer keys, then it's simple:
$theData = array();
for($i = 0; $i < count($e); ++$i) {
$theData[] = array(
'href' => $find[$i]->href,
'linkText' => $find[$i]->plaintext,
'description' => $findText[$i]->plaintext);
}
Note that the above code will not work correctly if $find
and $findText
don't have the same number of items, or if the keys don't match. Generally, making this work without more specific information will get quite messy.
The best practical advice I can give is to re-examine the code which creates $find
and $findText
-- it will be much easier to achieve your goal at that time.
Allow me to make the assumption that you are combining information from two queries. One option you have is to get href, linktext and description from your database all at once by joining your query.
select table_1.href,table_1.plaintext, table_2.plaintext
from table_1
where //insert your where clause, if appropriate
join table_2 on table_1.id = table_2.parent_id
where table one is your $find array and table_2 is your $findText array; and table_2.parent_id is a value matching the id from table_1. Joining the tables in this query will store all the fields from your two assumed queries into one variable.
精彩评论