I am trying to combine two arrays, as shown in picture there are two arrays one after another but IDs that are in circle are related and I would like to have bottom one nested into the first one, how can I achieve this. My code is here:
I would say that your āproblemā is actually in your query. I would suggest you post an SQL dump of your DB along with a few sample records and a detailed description of what you want to know about the data.
$query = 'SELECT lokacija.*, donacija.naziv FROM lokacija, donacija, donacija_lokacija WHERE donacija.id=donacija_lokacija.donacija_id AND donacija_lokacija.lokacija_id=lokacija.id ORDER BY lokacija.name';
Query looks like above and data is as on picture, I have three tables, third table is just keeping IDs of first two tables and bridging them. Most of the rows are repeated exactly same, the only different column is the last one ānazivā. And i want to output distinct rows while collecting different ānazivā values for the same ID and putting them in the array.
What end result (overall goal) do you want? Do you actually want a combined array for some reason (and what would that reason be?) or are you just trying to display this information, with each distinct location followed by a list of the donations for the location?
I think I figured out what you are trying to accomplish (the picture in the 1st post is confusing and couldnāt have come from the query you posted later.)
See if this produces a result that does what you want -
$posts_arr = array();
while($row = $result->fetch(PDO::FETCH_ASSOC))
{
if(!isset($posts_arr[$row['id']]))
{
// create an entry for each distinct location
$posts_arr[$row['id']] = $row; // note: this will contain the 1st 'naziv' value per location - not used.
}
// store the naziv values as a sub array in the location entry
$posts_arr[$row['id']]['donations'][] = $row['naziv'];
}
print_r($posts_arr);
Note: if you set the default fetch mode to assoc when you make the database connection, you wonāt have to specify it in each fetch statement.