0

Sql response seems like this: Name|Locality|Date|Address. Rows can contains same Name, Locality and Date, but Addres will be changed every time. So, I need put this response to array like this:

[0] => 'Name':'...',
       'Locality':'...',
       'Date':'...',
       'Address': [0] => '...',
                  [1] => '...',
                  [2] => '...',
                  ...
...

I have tryed to use this code, but is does't work =(

while($r = mysqli_fetch_assoc($q_res)){
    $i = 0;

    if(!in_array($r['watcher_name'], $daily_quests)){          
        $daily_quests[$i]['name'] = $r['name'];
        $daily_quests[$i]['date'] = $r['date'];
        $daily_quests[$i]['locality'] = $r['locality'];
    }
    else{
        $daily_quests['address'] = $intrnal_addr[$i => $r['address']];
    }

}
2
  • 1
    Post Database Table Structure and Data. Commented Aug 18, 2017 at 7:04
  • 1
    What does "doesn't work" mean? What is $r['watcher_name'], it's not mentioned in your db-structure? You're resetting $i on each iteration. That's the same as hard coding 0. Commented Aug 18, 2017 at 7:04

2 Answers 2

1

Try this :

//Initialisation
$name = '';
$daily_quests = array();
$i = -1;

while($r = mysqli_fetch_assoc($q_res)){

    //If the row is different than precedent
    if (strcmp($r['name'], $name) != 0)
    {
        $i++;
        $name = $r['name'];
        $daily_quests[$i] = array();
        $daily_quests[$i]['name'] = $r['name'];
        $daily_quests[$i]['date'] = $r['date'];
        $daily_quests[$i]['locality'] = $r['locality'];
        $daily_quests[$i]['address'] = array(); 
    }
    // For each row, we must add address
    $daily_quests[$i]['address'][] = $r['address']
}

However, we suppose that name is unique. It's more safe to compare with an id.

Sign up to request clarification or add additional context in comments.

Comments

0

You can solve this in the MySQL query by grouping it:

select
Name, Date, Locality, group_concat(Address SEPARATOR '|') as addresses
from __table__
group by Name, Date, Locality;

Then in php:

while($r = mysqli_fetch_assoc($q_res)){
    $r['Address'] = explode('|', $r['addresses']);
    unset($r['addresses']);
    $daily_quests[] = $r;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.