php циклы и группировка mysql - PullRequest
0 голосов
/ 16 июля 2010

Я сейчас добавляю раздел истории покупок в платежную систему, система построена на PHP (codeigniter framework) и mysql.Идея раздела истории платежей заключается в том, что все покупки клиентов сгруппированы по дате, поэтому в конце HTML-код будет выглядеть примерно так:

Мой вопрос: я могу получить данные из базы данных? Нетпроблема, но как я могу пройти по ней так, чтобы я показывал дату покупок, а затем покупки, относящиеся к этой дате, и т. д. и т. д. * РЕДАКТИРОВАТЬ - ПЕЧАТЬ ИЗ Массива, возвращенного изБД Извините за размер

    Array
(
    [0] => Array
        (
            [id] => 
            [employer_id] => 1
            [cv_id] => 
            [transaction_id] => -1402310
            [date_created] => 20-07-10
            [date_updated] => 
            [code] => 849711492
            [status] => SHOW
            [is_complete] => TRUE
            [job_status] => 1
            [dob] => 
            [will_relocate] => Y
            [education_level] => HIGH_SCHOOL
            [job_looking_for] => 
            [keywords_education] => Halifax University
            [keywords_employment] => senior applications developer
            [self_description] => 
            [looking_for] => Lorem ipsum
            [sector_id_csv] => 10,23,14,6,3
            [key_skills_csv] => 
            [expected_salary_level] => LEVEL_6
            [expected_salary_low] => 0
            [expected_salary_high] => 0
            [best_salary_low] => 0
            [best_salary_high] => 0
            [last_job_salary_low] => 
            [last_job_salary_high] => 
            [last_job_title_1] => Designer
            [last_job_title_2] => 
            [last_job_employer_1] => BT
            [last_job_employer_2] => 
            [qual_highest_level] => 0
            [is_grad] => Y
            [is_contract] => N
            [is_temporary] => Y
            [is_permanent] => Y
            [is_full_time] => Y
            [is_part_time] => Y
            [logitude] => 
            [latitude] => 
            [city] => 
            [area] => 
            [sign_up_stages_completed] => 
            [sign_up_last_stage_completed] => 
            [sign_up_complete] => 
            [email_authenticated] => 
            [email] => 
            [email_contact] => 
            [phone_contact_number] => 
            [password] => 
            [firstname] => 
            [surname] => 
            [address_1] => 
            [address_2] => 
            [address_3] => 
            [postcode] => 
            [country] => 
        )

    [1] => Array
        (
            [id] => 
            [employer_id] => 1
            [cv_id] => 
            [transaction_id] => -1402310
            [date_created] => 20-07-10
            [date_updated] => 
            [code] => 849719383
            [status] => SHOW
            [is_complete] => TRUE
            [job_status] => 1
            [dob] => 
            [will_relocate] => Y
            [education_level] => HIGH_SCHOOL
            [job_looking_for] => 
            [keywords_education] => Crewe Art School
            [keywords_employment] => senior applications developer
            [self_description] => 
            [looking_for] => Lorem ipsum
            [sector_id_csv] => 13,24,7,17,5
            [key_skills_csv] => 
            [expected_salary_level] => LEVEL_6
            [expected_salary_low] => 0
            [expected_salary_high] => 0
            [best_salary_low] => 0
            [best_salary_high] => 0
            [last_job_salary_low] => 
            [last_job_salary_high] => 
            [last_job_title_1] => Developer
            [last_job_title_2] => 
            [last_job_employer_1] => Orange
            [last_job_employer_2] => 
            [qual_highest_level] => 0
            [is_grad] => Y
            [is_contract] => N
            [is_temporary] => Y
            [is_permanent] => Y
            [is_full_time] => Y
            [is_part_time] => N
            [logitude] => 
            [latitude] => 
            [city] => 
            [area] => 
            [sign_up_stages_completed] => 
            [sign_up_last_stage_completed] => 
            [sign_up_complete] => 
            [email_authenticated] => 
            [email] => 
            [email_contact] => 
            [phone_contact_number] => 
            [password] => 
            [firstname] => 
            [surname] => 
            [address_1] => 
            [address_2] => 
            [address_3] => 
            [postcode] => 
            [country] => 
        )

    [2] => Array
        (
            [id] => 
            [employer_id] => 1
            [cv_id] => 
            [transaction_id] => 23-9-1402338
            [date_created] => 17-07-10
            [date_updated] => 
            [code] => 849711492
            [status] => SHOW
            [is_complete] => TRUE
            [job_status] => 1
            [dob] => 
            [will_relocate] => Y
            [education_level] => HIGH_SCHOOL
            [job_looking_for] => 
            [keywords_education] => Halifax University
            [keywords_employment] => senior applications developer
            [self_description] => 
            [looking_for] => Lorem ipsum
            [sector_id_csv] => 10,23,14,6,3
            [key_skills_csv] => 
            [expected_salary_level] => LEVEL_6
            [expected_salary_low] => 0
            [expected_salary_high] => 0
            [best_salary_low] => 0
            [best_salary_high] => 0
            [last_job_salary_low] => 
            [last_job_salary_high] => 
            [last_job_title_1] => Designer
            [last_job_title_2] => 
            [last_job_employer_1] => BT
            [last_job_employer_2] => 
            [qual_highest_level] => 0
            [is_grad] => Y
            [is_contract] => N
            [is_temporary] => Y
            [is_permanent] => Y
            [is_full_time] => Y
            [is_part_time] => Y
            [logitude] => 
            [latitude] => 
            [city] => 
            [area] => 
            [sign_up_stages_completed] => 
            [sign_up_last_stage_completed] => 
            [sign_up_complete] => 
            [email_authenticated] => 
            [email] => 
            [email_contact] => 
            [phone_contact_number] => 
            [password] => 
            [firstname] => 
            [surname] => 
            [address_1] => 
            [address_2] => 
            [address_3] => 
            [postcode] => 
            [country] => 
        )

    [3] => Array
        (
            [id] => 
            [employer_id] => 1
            [cv_id] => 
            [transaction_id] => 23-9-1402338
            [date_created] => 17-07-10
            [date_updated] => 
            [code] => 849719383
            [status] => SHOW
            [is_complete] => TRUE
            [job_status] => 1
            [dob] => 
            [will_relocate] => Y
            [education_level] => HIGH_SCHOOL
            [job_looking_for] => 
            [keywords_education] => Crewe Art School
            [keywords_employment] => senior applications developer
            [self_description] => 
            [looking_for] => Lorem ipsum
            [sector_id_csv] => 13,24,7,17,5
            [key_skills_csv] => 
            [expected_salary_level] => LEVEL_6
            [expected_salary_low] => 0
            [expected_salary_high] => 0
            [best_salary_low] => 0
            [best_salary_high] => 0
            [last_job_salary_low] => 
            [last_job_salary_high] => 
            [last_job_title_1] => Developer
            [last_job_title_2] => 
            [last_job_employer_1] => Orange
            [last_job_employer_2] => 
            [qual_highest_level] => 0
            [is_grad] => Y
            [is_contract] => N
            [is_temporary] => Y
            [is_permanent] => Y
            [is_full_time] => Y
            [is_part_time] => N
            [logitude] => 
            [latitude] => 
            [city] => 
            [area] => 
            [sign_up_stages_completed] => 
            [sign_up_last_stage_completed] => 
            [sign_up_complete] => 
            [email_authenticated] => 
            [email] => 
            [email_contact] => 
            [phone_contact_number] => 
            [password] => 
            [firstname] => 
            [surname] => 
            [address_1] => 
            [address_2] => 
            [address_3] => 
            [postcode] => 
            [country] => 
        )

)

В основном Каждый раз, когда появляются новые данные, мне нужно перечислить содержимое массива под ним, и, если два массива имеют одинаковые данные, перечислить их только под одним данным что-токак,

30-07-10

Результат 1
2
3

28-7-10

4
5

Ответы [ 2 ]

1 голос
/ 16 июля 2010

При использовании CodeIgniter один способ циклического просмотра результатов запроса выглядит следующим образом:

//if your doing your queries in a controller
$data['query']=$this->db->query('SELECT * FROM purchases WHERE clientID=5');

//or if using models
$data['query']=$this->pmnt_model->getPmnts();

//view
foreach($query result() as $row){
    echo $row->date;
}

переменная $query - это массив результатов, возвращаемый из запроса mysql.Доступ к объектам можно получить через оператор ->.

См. http://codeigniter.com/user_guide/database/results.html для получения дополнительной информации.

Вы также можете проверить активный класс записи .

HTH

0 голосов
/ 16 июля 2010

Есть две возможности, которые я вижу, чтобы выполнить то, что вам нужно. Вот один из них; отправьте на ваше рассмотрение два массива, один из которых содержит только даты, а другой - информацию о покупке:

В контроллере

$page_data['purchase_dates'] = $this->yourmodel->get_purchase_dates($record_id);
$page_data['purchases'] = $this->yourmodel->get_purchases($record_id);

Примечание Убедитесь, что вы используете GROUP BY в запросе к базе данных для дат покупки.

В представлении

<!-- Start Outer Tree Loop -->
<?php if($purchase_dates != FALSE){?>
<?php foreach($purchase_dates as $id=>$outer_value) { ?>
<!-- Output the date here -->
  <!-- Start Purchase table -->
  <table>
  <tr>
  <th>Param One</th>
  <th>Param Two</th>
  <th>Etcetera</th>
  <th></th>
  </tr>

  <!-- Start inner loop -->
  <?php foreach($purchases as $id=>$inner_value) { ?>
   <?php if($inner_value['purchase_date'] == $outer_value['purchase_date']) { ?>
    <tr>
    <td><?php echo $inner_value['Param One'] ?> </td>
    <td><?php echo $inner_value['Param Two'] ?></td>
    <td><?php echo $inner_value['Etcetera'] ?> </td>
   </tr>
   <?php  } ?>
  <?php  } ?>
  <!-- End inner loop -->

  </table>
  <!-- End Purchase table -->

<?php } ?>
<?php }?>
<!-- End Outer Tree Loop -->

Я добавил комментарии, чтобы проиллюстрировать код (это может быть лучшим вариантом для вас, так как размещенный вами массив является двухмерным).

Второе: - отправка трехмерного массива в представление и цикл по нему очень похожим образом, как указано выше.

<?php if($purchases != FALSE){?>
<?php foreach($purchases as $id=>$purchase_day) { ?>

<?php foreach($purchase_day as $purchase) { ?>

<!-- Output here -->

<?php } ?>

<?php } ?>
<?php }?>

Надеюсь, это поможет.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...