I am facing a problem problem here and need some help.
I have saved in my database a json_aray array with objects.
After decoding and print_r it I get this result.
Array (
[0] => stdClass Object (
[Title] => Image
[Info] => info
[ImageURL] => url.jpg )
[1] => stdClass Object (
[Title] => Image
[Info] => info
[ImageURL] => url.jpg )
[2] => stdClass Object (
[Title] => Accommodation
[Info] => info
[ImageURL] => image.jpg )
[3] => stdClass Object (
[Title] => Accommodation
[Info] => info
[ImageURL] => image.jpg )
[4] => stdClass Object (
[Title] => Accommodation
[Info] => info
[ImageURL] => image.jpg )
[5] => stdClass Object (
[Title] => Image
[Info] => info
[ImageURL] => image.jpg )
[6] => stdClass Object (
[Title] => Location
[Info] => info
[ImageURL] => image.jpg )
)
So here is the CASE:
I am trying to create a div for every different Object->Title e.g
I tried to check that with foreach loop but the result was creating 5 different divs instead of one.
Is there any built-in function in php to get all the $obj->Info if the $obj->Title == 'foo' or somehow check before the foreach loop what data the array has and separate them?
What i did in my code is below
while($row = sqlsrv_fetch_array($get_details)) {
$a = $row['additionalInformation'];
$b = json_decode($a);
$c = $b->AdditonalInfo;
foreach ($c as $d){
echo '<div class="class">';
if(($d->Title !== 'Image')){
echo '<h2>'.$d->Title.'</h2>';
echo '<p>'.$d->Info.'</p>';
}
echo "</div>";
}
}
UPDATE
Change my code with the actual one
This is what I get
But I need to create Accommodation or every same Title just once and all Info that has Title == 'Accommodation' under that div.
IF my question is clear enough please let me know so I can update it.
So to sum up i need to display all [Info] that has same [Title] in one div and create different div for each unique '[Title]'
Thanks In Advance
Requirements: Show 'nested groups' in a sequential stream of records.
Here we have a nested group indicated by a field called 'Title'.
The input records must be sorted so that all the records in each group are together and in the required order.
Now, the first thought is to use a 'foreach' loop. This is not the clearest approach because you cannot detect the end of the group by looking at the current record. Also, the foreach loop reads the next record at the end of the loop. So, you end up trying to work out where you are in the group to know what to do.
I use a technique called 'read ahead'. The idea is to read a record before the loop and the read the next record immediately after you have processed the current one. The 'trick' is that you process all the records in a group inside a loop.
So, the logic is an iteration of:
Process start of group - already has the first record of the group - important.
Process all the detail records belonging to the group - records are read inside this loop.
Process the end of the group - the current record is the first of the next group
repeat for each group.
It results in easier to understand code.
I have split all the separate actions into function so that you easily modify the individual actions.
Notice the code matches the structure of the data. There is always one place in the code to put the required action for that particular data item.
Full working Source Code at eval.in
Run the code
outputAllGroups($src);
exit();
Process All the Groups
function outputAllGroups(&$inputList)
{
reset($inputList);
$currentDetails = current($inputList); // read the first record
while ($currentDetails !== false) { // not end of records
// start the title group
$currentTitle = $currentDetails->Title;
outputGroupHeader($currentDetails);
// process all records in the group
while ( $currentDetails !== false
&& $currentDetails->Title === $currentTitle) {
outputDetails($currentDetails);
$currentDetails = readNextDetails($inputList); // may end group
}
// end the title group
outputGroupFooter($currentTitle);
}
}
Functions for the individual actions
function outputGroupHeader($details)
{
echo '<div class="TitleGroup">'. "<!-- Start Group: {$details->Title} -->". PHP_EOL
. '<div class="Title">'. $details->Title .'</div>' . PHP_EOL;
}
function outputGroupFooter($title)
{
echo '</div>'. "<!-- End Group: {$title} -->". PHP_EOL;
}
function outputDetails($details)
{
echo '<div class="details">'. PHP_EOL,
$details->Info . PHP_EOL,
$details->ImageURL .PHP_EOL,
'</div>' . PHP_EOL;
}
function readNextDetails(&$inputList)
{
$allOk = next($inputList); // advance next
return $allOk !== false ? current($inputList) : $allOk; // advance next
}
Output
<div class="TitleGroup"><!-- Start Group: Image -->
<div class="Title">Image</div>
<div class="details">
info1
url1.jpg
</div>
<div class="details">
info2
url2.jpg
</div>
</div><!-- End Group: Image -->
<div class="TitleGroup"><!-- Start Group: Accommodation -->
<div class="Title">Accommodation</div>
<div class="details">
info3
image3.jpg
</div>
<div class="details">
info4
image4.jpg
</div>
<div class="details">
info5
image5.jpg
</div>
</div><!-- End Group: Accommodation -->
<div class="TitleGroup"><!-- Start Group: Image -->
<div class="Title">Image</div>
<div class="details">
info6
image6.jpg
</div>
</div><!-- End Group: Image -->
<div class="TitleGroup"><!-- Start Group: Location -->
<div class="Title">Location</div>
<div class="details">
info7
image7.jpg
</div>
</div><!-- End Group: Location -->
Data
$src = Array (
'0' => (object) array(
'Title' => 'Image',
'Info' => 'info1',
'ImageURL' => 'url1.jpg', ),
'1' => (object) array(
'Title' => 'Image',
'Info' => 'info2',
'ImageURL' => 'url2.jpg', ),
'2' => (object) array(
'Title' => 'Accommodation',
'Info' => 'info3',
'ImageURL' => 'image3.jpg', ),
'3' => (object) array(
'Title' => 'Accommodation',
'Info' => 'info4',
'ImageURL' => 'image4.jpg', ),
'4' => (object) array(
'Title' => 'Accommodation',
'Info' => 'info5',
'ImageURL' => 'image5.jpg', ),
'5' => (object) array(
'Title' => 'Image',
'Info' => 'info6',
'ImageURL' => 'image6.jpg', ),
'6' => (object) array(
'Title' => 'Location',
'Info' => 'info7',
'ImageURL' => 'image7.jpg', ),
);
Hi please do so to get for each result unique div. For the 2 quetion (Is there any built-in function in php to get all the $obj->Info if the $obj->Title == 'foo' or somehow check before the foreach loop what data the array has and separate them?) I will find some solution late :)
$a = $row['additionalInformation'];
$b = json_decode($a);
$c = $b->AddInfo;
$createDivArray = array();
echo '<div class="style1">';
foreach ($c as $value){
if (in_array($value->Title, $createDivArray)) {
continue;
}
$createDivArray[] = $value->Title;
echo "<h4>$value->Title</h4>";
echo "<p>$value->Info</p>";
}
echo "</div>";
Related
I have created a tree level menu but I wanted to separate all sub menus by simply adding -- to every sub menu like
main menu
-- 1st level
---- 2nd level
------ 3rd level
and so on
while doing it in LI it is so easy I can simply put tag before running my function but in select option I am unable to achive my target can anyone here would be able to help me out with this please
function fetch_menu($data) {
foreach($data as $menu) {
echo "<option value='".$menu->cid."'>".$menu->cname."</option>";
if(!empty($menu->sub)) {
fetch_sub_menu($menu->sub);
}
}
}
function fetch_sub_menu($sub_menu, $dash = '--'){
foreach($sub_menu as $menu){
echo "<option value='".$menu->cid."'>".$dash.$menu->cname."</option>";
if(!empty($menu->sub)) {
fetch_sub_menu($menu->sub, '--');
}
}
}
The problem is that while applying the above shown code that dash are not increasing for every 2nd or 3rd level menu
Here is how my data is organized in array form
array (
[cid] => 1,
[cname] => 'Main Menu',
[pcid] => 0,
[sub] => array(
[cid] => 2,
[cname] => '1st Level',
[pcid] => 1,
[sub] => array(
[cid] => 3,
[cname] => '2nd Level',
[pcid] => 2,
[sub] => array(
)
)
)
)
You need to add the new dashes to your $dash variable before recursivly calling the function again. That should work
function fetch_sub_menu($sub_menu, $dash = '--'){
foreach($sub_menu as $menu){
echo "<option value='".$menu->cid."'>".$dash.$menu->cname."</option>";
if(!empty($menu->sub)) {
fetch_sub_menu($menu->sub, $dash.'--'); // <-- adding two dashes to $dash
}
}
}
I am trying to get away from doing things manually and repetitively by correctly utilizing loops and functions (methods) in oop programming; but I have hit a major stumbling block as it regards to multidimensional array groups, in passing the correct values to the necessary abstracted function (method) responsible for a database action.
Any help at all is very much welcomed and will enable me to move on from this stumbling block that I have been trying to push away for days upon days but without progress and it is out of true frustration and much agony that I am here begging for help.
Below is the code that for simplicity I have shortened as much as possible (can be easily tested locally by copying and pasting):
// array with table properties and form values - start
$form_fields_arr = [
'group' => [
'anime' => [ // genre
'table_prop' => [ // for update query - table properties
'table_name' => 'anime_tbl',
'account_id' => 2,
'visible' => 'yes'
],
'form_data' => [ // for update query - form values
'2' => 'Attack on Titan',
'4' => 'RWBY',
'6' => 'Rurouni Kenshin',
'8' => 'A Silent Voice'
]
],
'movie' => [ // genre
'table_prop' => [ // for update query - table properties
'table_name' => 'movie_tbl',
'account_id' => 4,
'visible' => 'yes'
],
'form_data' => [ // for update query - form values
'1' => 'Queen of Katwe',
'3' => 'Forest Gump',
'5' => 'War Horse',
'7' => 'The Fault in our Stars'
]
]
]
]; // ... end
// loop through multidimensional array and pass values to function - start
foreach ($form_fields_arr['group'] as $frm_key_1 => $frm_val_1) { // 2d array
foreach ($frm_val_1 as $frm_key_2 => $frm_val_2) { // 1d array
if (strcasecmp($frm_key_1, $frm_key_1) === 0) { // group by genre
foreach ($frm_val_2 as $frm_key_3 => $frm_val_3) { // 1d array
if (strcasecmp($frm_key_2, 'form_data') === 0) {
$title = $form_fields_arr['group'][$frm_key_1]['form_data'][$frm_key_3]; // anime/movie title
}
if (isset($frm_val_2['table_name']) &&
isset($frm_val_2['account_id']) &&
isset($frm_val_2['visible']) &&
isset($title)
) {
dbUpdate(
$frm_val_2['table_name'],
$frm_val_2['account_id'],
$frm_val_2['visible'],
$title
);
}
} // 1d array
} // if block
} // 1d array
} // 2d array
// ... end
// function that receives passed values - start
function dbUpdate($table_name, $account_id, $title_col, $form_value) {
$test_val_arr = [$table_name, $account_id, $title_col, $form_value];
return print_r($test_val_arr);
} // ... end
The above code outputs:
// array values passed to and returned from function
Array (
[0] = movie_tbl
[1] = 4
[2] = yes
[3] = A Silent Voice
)
Array (
[0] = movie_tbl
[1] = 4
[2] = yes
[3] = A Silent Voice
)
Array (
[0] = movie_tbl
[1] = 4
[2] = yes
[3] = A Silent Voice
)
Array (
[0] = movie_tbl
[1] = 4
[2] = yes
[3] = A Silent Voice
)
But the desired result that I am trying to achieve is:
// for anime genre - array values passed to and returned from function
Array (
[0] = anime_tbl
[1] = 2
[2] = yes
[3] = Attack on Titan
)
Array (
[0] = anime_tbl
[1] = 2
[2] = yes
[3] = RWBY
)
Array (
[0] = anime_tbl
[1] = 2
[2] = yes
[3] = Rurouni Kenshin
)
Array (
[0] = anime_tbl
[1] = 2
[2] = yes
[3] = A Silent Voice
)
// for movie genre - array values passed to and returned from function
Array (
[0] = movies_tbl
[1] = 4
[2] = yes
[3] = Queen of Katwe
)
Array (
[0] = movies_tbl
[1] = 4
[2] = yes
[3] = Forest Gump
)
Array (
[0] = movies_tbl
[1] = 4
[2] = yes
[3] = War Horse
)
Array (
[0] = movies_tbl
[1] = 4
[2] = yes
[3] = The Fault in our Stars
)
so upon everything royally failing with me spending literally about a week trying to fix this, telling myself that it is very simple and I really shouldn't be stuck here, out of desperation I decided to go back to my repetitive ways and tried the following:
// new array without table properties - start
$new_array = [];
$new_array['group']['anime'] = $form_fields_arr['group']['anime']['form_data'];
$new_array['group']['movie'] = $form_fields_arr['group']['movie']['form_data']; // ... end
// loop through multidimensional array and pass values to function - start
foreach ($new_array['group'] as $key_1 => $val_1) { // 2d array
foreach ($val_1 as $key_2 => $val_2) { // 1d array
if (strcasecmp($key_1, $key_1) === 0) {
dbUpdate('anime_tbl', 2, 'yes', $val_2);
dbUpdate('movie_tbl', 4, 'yes', $val_2);
} // if block
} // 1d array
} // 2d array
// ... end
But the results are still very much undesirable. Everything was working fine until I started using multidimensional arrays, simply because I realized that utilizing multidimensional arrays help me to shorten my code in other areas considerably. But I am stuck here and will have to go back further up and undo quite a lot of changes if I can't get this to work. I am pleading for help from any good soul out there. Please help me someone! Anyone!
I am being optimistic here and assuming that if by any chance I do get some help in fixing the above problem, could someone please also teach me how to loop through an array structure like the one below while yet getting the desired results without duplicates (I have truly tried but have truly failed):
// array with table properties and form values - start
$form_fields_arr = [
'table_prop' => [ // table properties group
'anime' => [ // for update query - table properties
'table_name' => 'anime_tbl',
'account_id' => 2,
'visible' => 'yes'
],
'movie' => [ // for update query - table properties
'table_name' => 'movie_tbl',
'account_id' => 4,
'visible' => 'yes'
]
],
'form_data' => [ // for update query - form values
'anime' => [ // genre
'2' => 'Attack on Titan',
'4' => 'RWBY',
'6' => 'Rurouni Kenshin',
'8' => 'A Silent Voice'
],
'movie' => [ // genre
'1' => 'Queen of Katwe',
'3' => 'Forest Gump',
'5' => 'War Horse',
'7' => 'The Fault in our Stars'
]
]
]; // ... end
You got a logic mistake in your for loops. First of all your variable namings are not very intuitive. $frm_key_1, $frm_key_2, etc. look alike and force the reader to have the array structure in mind all the time to understand the variables meaning. This led to a mistake like this one: if( strcasecmp($frm_key_1, $frm_key_1) === 0 ). This is always true.
Then you had two exclusive conditions:
if (strcasecmp($frm_key_2, 'form_data') === 0)
And:
if (isset($frm_val_2['table_name']) && /* ... */) {
If $frm_key_2 is 'form_data' you are in the second child of the genre array, yet the fields 'table_name', etc. are defined only in the first one (witht the key 'table_prop'). So both conditions can never be true at the same time.
Your condition to trigger the dbUpdate() function was, that all fields of the 'table_prop' array were present (which you iterated through at the same time), and a $title was set aswell. This was only true after your third for-loop iterated for the second time. During that iterations the $title variable got overwritten constantly, but no sbUpdate() was triggered, because $frm_val_2 had the values from 'form_data' instead of 'table_prop'. So after the 3rd for loop finished the 2nd time $title was 'A Silent Voice', which is simply the last child of the first 'form_data' array. Afterwards your 2nd for loop iterated the 2nd 'table_prop' array again, which means that now the 'dbUpdate()' condition was true, so it postet 4 times (number of childs in the 'table_prop' array) the parameters with $title = 'A Silent Voice'.
You tried to make everything as generic as possible, making everything over complicated. The best solution that works here is one that respects the specific structure.
This works:
<?php
// array with table properties and form values - start
$form_fields_arr = [
'group' => [
'anime' => [ // genre
'table_prop' => [ // for update query - table properties
'table_name' => 'anime_tbl',
'account_id' => 2,
'visible' => 'yes'
],
'form_data' => [ // for update query - form values
'2' => 'Attack on Titan',
'4' => 'RWBY',
'6' => 'Rurouni Kenshin',
'8' => 'A Silent Voice'
]
],
'movie' => [ // genre
'table_prop' => [ // for update query - table properties
'table_name' => 'movie_tbl',
'account_id' => 4,
'visible' => 'yes'
],
'form_data' => [ // for update query - form values
'1' => 'Queen of Katwe',
'3' => 'Forest Gump',
'5' => 'War Horse',
'7' => 'The Fault in our Stars'
]
]
]
];
// loop through multidimensional array and pass values to function - start
foreach ($form_fields_arr['group'] as $genreData) {
$tableProperties = $genreData['table_prop'];
if (!isset($tableProperties['table_name'])
|| !isset($tableProperties['account_id'])
|| !isset($tableProperties['visible'])) {
continue;
}
$data = $genreData['form_data'];
foreach ($data as $title) {
dbUpdate(
$tableProperties['table_name'],
$tableProperties['account_id'],
$tableProperties['visible'],
$title
);
}
}
// function that receives passed values - start
function dbUpdate($table_name, $account_id, $title_col, $form_value) {
$test_val_arr = [$table_name, $account_id, $title_col, $form_value];
return print_r($test_val_arr);
} // ... end
For the last part of the question that wasn't answered, thanks to Philipp Maurer's answer, after playing around with the code I got it to work. I am just placing the answer here for anyone who might have a similar problem and would like to better understand how to group and fetch values from a multidimensional array using a foreach loop without duplicates or incorrect results. See below code:
// array with table properties and form values - start
$form_fields_arr = [
'table_prop' => [ // table properties group
'anime' => [ // for update query - table properties
'table_name' => 'anime_tbl',
'account_id' => 2,
'visible' => 'yes'
],
'movie' => [ // for update query - table properties
'table_name' => 'movie_tbl',
'account_id' => 4,
'visible' => 'yes'
]
],
'form_data' => [ // for update query - form values
'anime' => [ // genre
'2' => 'Attack on Titan',
'4' => 'RWBY',
'6' => 'Rurouni Kenshin',
'8' => 'A Silent Voice'
],
'movie' => [ // genre
'1' => 'Queen of Katwe',
'3' => 'Forest Gump',
'5' => 'War Horse',
'7' => 'The Fault in our Stars'
]
]
]; // ... end
// loop through multidimensional array and pass values to function - start
foreach ($form_fields_arr as $index => $group_array) {
foreach ($group_array as $genre_key => $genre_val) {
if (!isset($group_array[$genre_key]['table_name']) ||
!isset($group_array[$genre_key]['account_id']) ||
!isset($group_array[$genre_key]['visible'])
) {
continue;
}
foreach ($form_fields_arr['form_data'][$genre_key] as $data_key => $data_title) {
dbUpdate(
$group_array[$genre_key]['table_name'],
$group_array[$genre_key]['account_id'],
$group_array[$genre_key]['visible'],
$data_title
);
}
}
}
// ... end
// function that receives passed values - start
function dbUpdate($table_name, $account_id, $title_col, $form_value) {
$test_val_arr = [$table_name, $account_id, $title_col, $form_value];
return print_r($test_val_arr);
} // ... end
I have a problem to view some data in the way I want to have it.
Here is a example of the array:
$items =
0 => [
'name' => 'foo'
'description' => 'bar'
'url' => 'http://foobar.com'
'headline' => 'Headline 1'
],
1 => [
'name' => 'uni'
'description' => 'corn'
'url' => 'http://unicorn.com'
'headline' => 'Headline 1'
],
2 => [
'name' => 'awe'
'description' => 'some'
'url' => 'http://awesome.com'
'headline' => 'Headline 2'
],
And know I want to loop through the items array and want to show the headline at first and all items that have the same headline. If a item has another headline, I want to print out the other headline and the items that belongs to it.
Should look like that:
Headline 1 : <--- Items that do have this headline
name = foo
description = bar
url = http://foobar.com
name = uni
description = corn
url = http://unicorn.com
Headline 2 <----- items with a new headline
name = awe
description = some
url = http://awesome.com
I wansn't able to do that. Can someone help me there?
I've tried something like a for loop that checks the current headline with the next headline.
#for ($i = 0; $i <= count($items); $i++)
<span>{{ $items[$i]['headline'] }}</span>
#if($items[$i]['headline'] == $items[$i+1]['headline'])
.....
# else .....
#endfor
But this haven't worked well
Thanks for your help and sorry because of my bad english!
Use laravel collections with groupby() method
$collection = collect($items);
$items= $collection->groupBy('headline');
$items->toArray();
The array will be splited by headline
From Laravel Docs https://laravel.com/docs/5.4/collections#method-groupby
If your array was a collection before converting to an array, you could use groupBy() collection method:
$collection->groupBy('headline');
Maybe this could help. i am writing this code in core PHP
$arr = array();
foreach($items as $item) {
$arr[$item['headline']] = $item;
}
it will return you an array of something like
Array
(
[Headline 1] => Array
(
[name] => uni
[description] => corn
[url] => http://unicorn.com
[headline] => Headline 1
)
[Headline 2] => Array
(
[name] => awe
[description] => some
[url] => http://awesome.com
[headline] => Headline 2
)
)
TL;DR
I'm trying to loop all the rows and output it with html. When I'm looping it, I get an array with the properties and values of a single row which is also the last row, when I do not loop it, I get 2 arrays (each array is a row) within an array. For some reason it doesn't loop it and display all the rows as it should, how do I fix this?
I'm trying to make a loop of sections and the articles within them, where as each article has a parent section.
In the database, there are 5 sections and 2 articles, article #1 has section #1 as it's parent and article #2 has section #2 as it's parent.
When print it as an array without looping it, I get the following array;
Array
(
[0] => Array
(
[s_id] => 1
[s_name] => News
[s_slug] => news
[s_visibility] => 1
[s_type] => 1
[s_status] => 1
[s_permission] => 0
[s_external] => 0
[s_location] => news
[s_color] => 1
[s_homepage] => 1
[a_id] => 1
[a_section] => 1
[a_title] => Ted Cruz’s ‘Secret’ Skill That No President Has Likely Had Since Thomas Jefferson
[a_description] => Apparently Cruz, whose famed 2013 marathon filibuster speech over defunding Obamacare jumped across a range of topics, has an uncanny capability to remember things he hears verbatim.
[a_content] => Apparently Cruz, whose famed 2013 marathon filibuster speech over defunding Obamacare jumped across a range of topics, has an uncanny capability to remember things he hears verbatim.
[a_views] => 0
[a_visibility] => 1
[a_date] => 17.11.2015
[a_author] => 1632422528
[a_category] => 1
[a_slug] =>
)
[1] => Array
(
[s_id] => 2
[s_name] => VOD
[s_slug] => vod
[s_visibility] => 1
[s_type] => 2
[s_status] => 1
[s_permission] => 0
[s_external] => 0
[s_location] => vod
[s_color] => 2
[s_homepage] => 1
[a_id] => 2
[a_section] => 2
[a_title] => GTA V PC Edition Released
[a_description] => Wondering where the score is? Our GTA Online review will remain scoreless, as a score does not properly reflect its continuously changing nature. Here's how and why we decided to do it this way.
[a_content] => Wondering where the score is? Our GTA Online review will remain scoreless, as a score does not properly reflect its continuously changing nature. Here's how and why we decided to do it this way.
[a_views] => 0
[a_visibility] => 1
[a_date] => 19.11.2015
[a_author] => 1632422528
[a_category] => 1
[a_slug] =>
)
)
But when I run it into a foreach loop, it outputs only a single array which is the later one (1).
I'm using CodeIgniter 3, the loop is inside a library called "Global_functions",
The model is "Functions_model".
Global_functions (only the related function, not the entire class because it contains other unrelated functions):
public function get_homepage_sections()
{
$getHomeData = $this->CI->functions_model->get_homepage_data();
foreach ($getHomeData as $get_sections)
{
switch ($get_sections['s_color'])
{
case 1:
$sectionColor = "blue";
break;
case 2:
$sectionColor = "purple";
break;
case 3:
$sectionColor = "orange";
break;
case 4:
$sectionColor = "green";
break;
default:
$sectionColor = "";
break;
}
$outputData = '
<li>
<div><h2 class="category ' . $sectionColor . '">' . $get_sections['s_name'] . '</h2></div>';
$outputData .= '
</li>';
}
return $get_sections;
}
Functions_model;
public function get_homepage_data()
{
$selected_columns = array(
'sections.s_id',
'sections.s_name',
'sections.s_slug',
'sections.s_visibility',
'sections.s_type',
'sections.s_status',
'sections.s_permission',
'sections.s_external',
'sections.s_location',
'sections.s_color',
'sections.s_homepage',
'articles.a_id',
'articles.a_section',
'articles.a_title',
'articles.a_description',
'articles.a_content',
'articles.a_views',
'articles.a_visibility',
'articles.a_date',
'articles.a_author',
'articles.a_category',
'articles.a_slug'
);
$query = $this->db->select( $selected_columns )
->from( config_item('sections') . ', ' . config_item('articles') )
//->join( config_item('articles'), 'articles.a_section = sections.s_id' )
->where( 'articles.a_section = sections.s_id' )
//->or_where( 'user_email', $user_string )
->get();
if ( $query->num_rows() >= 1 )
{
return $query->result_array();
}
}
Being called from the controller as follows (homepageSection);
public function index()
{
/* if ($this->require_role('admin')) {
echo $this->load->view('examples/page_header', '', TRUE);
echo '<p>You are logged in!</p>';
echo $this->load->view('examples/page_footer', '', TRUE);
}*/
// return $isAutoRememberMe;
//extra_for_auth();
// Call a function of the model
$data['getGlobalMessage'] = $this->global_functions->get_global_message();
$data['userOptions'] = $this->global_functions->extra_for_auth();
$data['homepageSection'] = $this->global_functions->get_homepage_sections();
//print_r ($data);
$this->parser->parse('template/header', $data);
$this->parser->parse('sections/homepage', $data);
$this->load->view('template/footer');
}
section/homepage file contains the call {homepageSection}, as you can see the parser is called and parses the file rather than loading it with view().
I think there is an error in get_home_sections()
instead of:
return $get_sections;
you should:
return $getHomeData
you are returning the last item from the array, that looks like the problem you stated.
Another point i see a little bit confusing is the var you are cummulating html.
$outputData is being reset in each loop, and you are not doing nothing with it. It's a good idea to initialize it at the begining of the funcion as empty string
$outputData = '';
and in the loop you should do an additive assingment with .=
Im trying to save a record to a table aswell as an accociated record. The main table is called quotes and it has a hasmany link to the table quote_items. quote_items belongsto quote
When i try and save it saves the record in quote but does not save the record in quote_items
.
Below is my quote add function
function add() {
if (!empty($this->data)) {
$this->Quote->create();
if ($this->Quote->saveAll($this->data)) {
$this->Session->setFlash(__('The Quote has been saved', true));
//$this->redirect(array('action'=>'index'));
} else {
$this->Session->setFlash(__('The Quote could not be saved. Please, try again.', true));
}
}
$this->Quote->recursive = 2;
$statuses = $this->Quote->Status->find('list');
$contacts = $this->Quote->Contact->find('list');
$this->set(compact('statuses', 'contacts'));
}
Quote view / form setup
<?php echo $form->create('Quote', array('action' => 'add'));?>
<fieldset>
<legend><?php __('Add Quote');?></legend>
<?php
echo $form->input('Quote.name');
echo $form->input('Quote.revision');
echo $form->input('Quote.status_id');
echo $form->input('Quote.contact_id');
echo $form->input('quote_item.product_id');
echo $form->input('quote_item.name');
echo $form->input('quote_item.price');
echo $form->input('quote_item.description');
echo $form->input('Quote.totalcost');
?>
</fieldset>
<?php echo $form->end('Submit');?>
Array that is returned when the form is submitted
Array (
[quote] => Array (
[name] => Test
[revision] => 1
[status_id] => 1
[contact_id] => 1
[totalcost] => 123
)
[quote_item] => Array (
[product_id] => 1
[name] => test
[price] => 123
[description] => tes 1234
)
)
This seems to follow exactly what is listed in the cakephp documentation so i cant work out why its not working - http://book.cakephp.org/view/84/Saving-Related-Model-Data-hasOne-hasMany-belongsTo
Thanks in advance
The correct way to build the form would be:
echo $form->input('Quote.name');
...
echo $form->input('QuoteItem.0.product_id');
echo $form->input('QuoteItem.0.name');
...
echo $form->input('QuoteItem.1.product_id');
echo $form->input('QuoteItem.1.name');
The resulting array should look like this:
array(
'Quote' => array(
'name' => 'Test'
....
),
'QuoteItem' => array(
0 => array(
'product_id' => 1
'name' => 'test'
...
)
1 => array(
'product_id' => 2
'name' => 'test'
...
)
)
)
According to naming conventions, model names are camelized (ModelName, not model_name). Also, since Quote hasMany QuoteItems, the QuoteItem array needs to consist of many QuoteItem arrays. Hope that makes sense. :)