1

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?

Uffo
  • 9,628
  • 24
  • 90
  • 154

3 Answers3

2

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++;
}
Dejan Marjanović
  • 19,244
  • 7
  • 52
  • 66
  • it kinda works, but as i've said above the description array it's smaller(has less integers) then the other one...so it has the same description for each array integer..it only adds the first description to all elements – Uffo Apr 03 '11 at 19:48
  • @Uffo I have added `[]` on `$data[$i]["description"]`, that is what you want If get it right. Print $data later and see. – Dejan Marjanović Apr 03 '11 at 19:53
  • @Uffo, this is easy, you'll catch it with time, thanks anyway :) – Dejan Marjanović Apr 03 '11 at 20:29
2

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.

Jon
  • 428,835
  • 81
  • 738
  • 806
  • Well that variable that holds the description sometimes can be empty so I need to prepad NULL insted....how can I do that? 'Cause I need to respect the array structure.thx – Uffo Apr 03 '11 at 19:37
1

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.

kevtrout
  • 4,934
  • 6
  • 33
  • 33