I've been using codeigniter for years but there's a really big gap in between so i always find myself in situations where i forgot how to do things and its almost midnight here so my brain isn't working fast. Can someone show me how to echo the array i have and explain to me how they are processed in the foreach loops?
I have this code in my model to take the rows in 2 tables.
public function tag_genre(){
$result['tag'] = $this->db->get('tags')->result_array();
$result['genre'] = $this->db->get('genre')->result_array();
return $result;
}
And I have this in my controller
public function view_publish_story(){
$data = array('tag_genre' => $this->story_model->tag_genre(), 'title' => "New Story");
$this->load->view('template/header',$data);
$this->load->view('template/navbar');
$this->load->view('pages/storypublish',$data);
$this->load->view('template/footer');
}
I used print_r in my view and this is the result. Seeing this just confuses me more. It's been atleast 2 years since i even dealt with foreach loops.
Array ( [tag] => Array ( [0] => Array ( [tag_id] => 1 [tag_name] =>
LitRPG ) [1] => Array ( [tag_id] => 2 [tag_name] => Virtual Reality )
[2] => Array ( [tag_id] => 3 [tag_name] => Cyberpunk ) [3] => Array (
[tag_id] => 4 [tag_name] => Reincarnation ) [4] => Array ( [tag_id] =>
5 [tag_name] => Summoned Hero ) [5] => Array ( [tag_id] => 6
[tag_name] => Martial Arts ) [6] => Array ( [tag_id] => 7 [tag_name]
=> Slice of Life ) [7] => Array ( [tag_id] => 8 [tag_name] => Overpowered ) [8] => Array ( [tag_id] => 9 [tag_name] => Non-Human )
[9] => Array ( [tag_id] => 10 [tag_name] => Anti-hero ) ) [genre] =>
Array ( [0] => Array ( [genre_id] => 1 [genre_name] => action ) [1] =>
Array ( [genre_id] => 2 [genre_name] => adventure ) [2] => Array (
[genre_id] => 3 [genre_name] => comedy ) [3] => Array ( [genre_id] =>
4 [genre_name] => Drama ) [4] => Array ( [genre_id] => 5 [genre_name]
=> Fantasy ) [5] => Array ( [genre_id] => 6 [genre_name] => Historical ) [6] => Array ( [genre_id] => 7 [genre_name] => Horror ) [7] => Array
( [genre_id] => 8 [genre_name] => Psychological ) [8] => Array (
[genre_id] => 9 [genre_name] => Romance ) [9] => Array ( [genre_id] =>
10 [genre_name] => Sci-fi ) [10] => Array ( [genre_id] => 11
[genre_name] => Mystery ) [11] => Array ( [genre_id] => 12
[genre_name] => Tragedy ) [12] => Array ( [genre_id] => 13
[genre_name] => Short Story ) [13] => Array ( [genre_id] => 14
[genre_name] => Satire ) ) )
I've been looking at various questions regarding arrays from assoc to multidimensional and other stuff. Then i finally visited php manual for foreach loop and i finally was able to echo the array. The problem now is that although it echoes my array it also has an error for each, i can probably fix the error part by declaring it as a defined variable. My question is, is there any other better way? or any improvement on how i made my array to make it cleaner or easier to print?
foreach($tag_genre as $key => $value){
foreach($value as $values){
echo $values['tag_name'];
}
}
UPDATE: i changed the way i made the array.
This is now my model:
public function get_tags(){
$query = $this->db->get('tags')->result_array();
foreach($query as $row){
$result[$row['tag_id']] = $row['tag_name'];}
return $result;
}
public function get_genre(){
$query = $this->db->get('genre')->result_array();
foreach($query as $row){
$result[$row['genre_id']] = $row['genre_name'];}
return $result;
}
and my controller:
public function view_publish_story(){
$data = array('tag' => $this->story_model->get_tags(), 'genre' => $this->story_model->get_genre(), 'title' => "New Story");
$this->load->view('template/header',$data);
$this->load->view('template/navbar');
$this->load->view('pages/storypublish',$data);
$this->load->view('template/footer');
}
and in my view:
<tr>
<div class="form-group">
<td><label for="genre">Genre</label></td>
<?php
foreach($genre as $genre_id => $genre_name){
echo "<td><label class='checkbox-inline'><input type='checkbox' value=''>".$genre_name."</label><td>";
}
?>
</div>
</tr>
My problem now is that, how do i fit all these into my table? I just ruined my table right now since i echoed them all in a single line. How do i do it so that it is printed in 3 columns?
foreach($tag_genre as $key => $value){
foreach($value as $values){
echo '<pre>';
echo $values['tag_name'];
}
}
this will format your array in a way you can read it and understand it.
Related
This question already has answers here:
Sort an array of associative arrays by column value
(23 answers)
Closed 2 years ago.
I want to sort a nested array by number. So that in each category the products with the biggest number comes first.
I tried something i found here.
How to Sort Multi-dimensional Array by Value?
usort($myArray, function($a, $b) {
$retval = $a['order'] <=> $b['order'];
if ($retval == 0) {
$retval = $a['suborder'] <=> $b['suborder'];
if ($retval == 0) {
$retval = $a['details']['subsuborder'] <=> $b['details']['subsuborder'];
}
}
return $retval;
});
but found no solution to make it work. Especially because i don't know each productnumber (e.g.sdk38z3) inside one category (e.g. chocholate - sugar - candy).
In my case i used uasort instead of usort.
Array
(
[apple - oranges - bananas] => Array
(
[fn7z3] => Array
(
[slider_details] =>
[productnumber] => fn7z3
[category] =>
[title] =>
[text] =>
[picture] =>
[number] => 30
[oneString] =>
)
)
[chocholate - sugar - candy] => Array
(
[sdk38z3] => Array
(
[slider_details] =>
[productnumber] => sdk38z3
[category] =>
[title] =>
[text] =>
[picture] =>
[number] => 45
[oneString] =>
)
[g433] => Array
(
[slider_details] =>
[productnumber] => g433
[category] =>
[title] =>
[text] =>
[picture] =>
[number] => 2
[oneString] =>
)
[j8z28] => Array
(
[slider_details] =>
[productnumber] => j8z28
[category] =>
[title] =>
[text] =>
[picture] =>
[number] => 250
[oneString] =>
)
[73hf873] => Array
(
[slider_details] =>
[productnumber] => 73hf873
[category] =>
[title] =>
[text] =>
[picture] =>
[number] => 30
[oneString] =>
)
)
Result i want:
Array
(
[apple - oranges - bananas] => Array
(
[fn7z3] => Array
(
[slider_details] =>
[productnumber] => fn7z3
[category] =>
[title] =>
[text] =>
[picture] =>
[number] => 30
[oneString] =>
)
)
[chocholate - sugar - candy] => Array
(
[j8z28] => Array
(
[slider_details] =>
[productnumber] => j8z28
[category] =>
[title] =>
[text] =>
[picture] =>
[number] => 250
[oneString] =>
)
[sdk38z3] => Array
(
[slider_details] =>
[productnumber] => sdk38z3
[category] =>
[title] =>
[text] =>
[picture] =>
[number] => 45
[oneString] =>
)
[73hf873] => Array
(
[slider_details] =>
[productnumber] => 73hf873
[category] =>
[title] =>
[text] =>
[picture] =>
[number] => 30
[oneString] =>
)
[g433] => Array
(
[slider_details] =>
[productnumber] => g433
[category] =>
[title] =>
[text] =>
[picture] =>
[number] => 2
[oneString] =>
)
)
I finally found a solution for my problem, by using a function given in this answer:
How to sort an array of associative arrays by value of a given key in PHP?
Because i don't really know the key i need i used a foreach loop with the $key functionality.
I needed to override my actual array with the sorted array too, to make changes permanent.
In my case, as i said, im using uasort instead of usort, because im using names as Key.
Explanation of variables:
$similarProducts = my whole array.
$attributeCombination = for Example [apple - oranges - bananas]
function invenDescSort($item1, $item2)
{
if ($item1['number'] == $item2['number']) return 0;
return ($item1['number'] < $item2['number']) ? 1 : -1;
}
foreach ($similarProducts AS $key => $attributeCombination) {
uasort($attributeCombination, 'invenDescSort');
$this->similarProducts[$key] = $attributeCombination;
//print_r($attributeCombination);
}
I have made researches and havent fount any solutions for this yet. So final thought is come to Stackoverflow and ask the question.
I have 2 array like below:
BigArray
Array
(
[0] => Array
(
[id] => 1
[category_name] => Accountancy
[category_name_vi] => Kế toán
[category_id] => 1
)
[1] => Array
(
[id] => 2
[category_name] => Armed forces
[category_name_vi] => Quân đội
[category_id] => 2
)
[2] => Array
(
[id] => 3
[category_name] => Admin & Secretarial
[category_name_vi] => Thư ký & Hành chính
[category_id] => 3
)
[3] => Array
(
[id] => 4
[category_name] => Banking & Finance
[category_name_vi] => Tài chính & Ngân hàng
[category_id] => 4
)
)
and SmallArray:
Array
(
[0] => Array
(
[id] => 7
[category_id] => 2
[jobseeker_id] => 1
)
[1] => Array
(
[id] => 8
[category_id] => 3
[jobseeker_id] => 1
)
)
Ok, now I wanted to match each category_id from SmallArray link with respectively category_name from BigArrayand the output I only need matched values between SmallArray and BigArraywhere category_id of SmallArray is key and category_name of BigArray is value like below:
Matched array:
Array
(
[0] => Array
(
[2] => Armed forces
)
[1] => Array
(
[3] => Admin & Secretarial
)
)
So far, I have tried array_intersect, 2 foreach loops but no luck. Any advise would be very appreciated :(
Thanks
This should do that:
foreach ($smallArray as $smallKey => $smallElement) {
foreach ($bigArray as $bigKey => $bigElement) {
if ($bigElement['id'] == $smallElement['category_id']) {
$smallArray[$smallKey] = array(
$bigElement['id'] => $bigElement['category_name'],
);
break; // for performance and no extra looping
}
}
}
After these loops, you have what you want in $smallArray.
I have 2 arrays inside the class Continente..both public and i populate the arrays with records from mysql database.
class Continente{
public $continente = array();
public $tari= array();
}
And i have an object for wich i call the methods to put data into my arrays.
$cont = new Continente;
$cont->setContinente();
$cont->setTari();
Now the arrays look like this:
Array (
[0] => Array ( [Id] => 1 [Nume] => Europa )
[1] => Array ( [Id] => 2 [Nume] => Asia )
[2] => Array ( [Id] => 3 [Nume] => Africa ) )
and:
Array
( [0] => Array ( [Id] => 0 [Nume] => Romania [idContinent] => 1 [Populatie] => 2500 )
[1] => Array ( [Id] => 0 [Nume] => Bulgaria [idContinent] => 1 [Populatie] => 2200 )
[2] => Array ( [Id] => 0 [Nume] => Estonia [idContinent] => 1 [Populatie] => 1100 )
[3] => Array ( [Id] => 0 [Nume] => Japonia [idContinent] => 2 [Populatie] => 5000 )
[4] => Array ( [Id] => 0 [Nume] => China [idContinent] => 2 [Populatie] => 4599 )
[5] => Array ( [Id] => 0 [Nume] => India [idContinent] => 2 [Populatie] => 6000 )
[6] => Array ( [Id] => 0 [Nume] => Egipt [idContinent] => 3 [Populatie] => 444 ) )
now i need to make a combox with the 3 continents , and for each continent selected i need to print the first 3 countries sorted by the bigest number in 'Populatie' .
So i can select the contries for the continents... i have Id=idContinent .
Now i really don't know how to do this. Write a method for this in php? As i already have the arrays... or html?
This is what i tried:
<html>
<head></head>
<body>
<div>
<br>
<select>
<?php
foreach($cont->tari as $val ){
echo '<option value="'.$val.'">'.$val.'</option>';
}
?>
</select>
</div>
</body>
</html>
If you can do it, I think you can clean up your data structure quite a bit and it would make it easier to accomplish what you are trying to do. If you store your information like this:
$data = array( Europa => array (Romania => 2500,
Bulgaria => 2200,
Estonia => 1100 ),
Asia => array ( Japonia => 5000,
China => 4599,
India => 6000 )
...);
Then you may be able to eliminate the need for your "ID" keys and just use the array indices for your IDs.
Then you can just sort your subarrays by value using arsort(). Something like this:
foreach( $data as $cont => $pop_data ) {
arsort( $pop_data );
}
Then for creating your combo boxes, use similar code:
foreach( $data as $cont => $pop_data ) {
echo $cont . " Population Info:" . "<br>"; // or whatever
foreach( $pop_data as $country => $pop ) {
echo '<option value="'.$pop.'">'.$pop.'</option>';
}
}
I have the following code:
<?php
//The company_array:
$company_array = array(
"AAA" => "AAA",
"BBB" => "BBB",
"CCC" => "CCC",
"DDD" => "DDD"
);
$platform_data = 'PC'; //Just to keep it short :)
foreach ($company_array as $company) {
if ($stmt = $mysqli->prepare("SELECT price, time FROM $company WHERE platform = ? ORDER BY time ASC")) {
$stmt->bind_param("s", $platform_data);
$stmt->execute();
$stmt->bind_result($price[$company], $time[$company]);
$i=0;
while ($stmt->fetch()) {
$company_info[$company][$i] = array('Price' => $price[$company], 'Time' => $time[$company]);
$i++;
}
$stmt->close();
}
?>
Now I had some issues with this, the last iteration of the loop seems to break, if I print $company_info all but the last company displays fine, the last one seem to repeat the last value for all the rows:
Array
(
[AAA] => Array
(
[0] => Array
(
[Price] => 626.8600
[Time] => 2013-09-27 14:30:06
)
[1] => Array
(
[Price] => 615.5900
[Time] => 2013-09-27 15:45:05
)
[2] => Array
(
[Price] => 604.7400
[Time] => 2013-09-27 17:45:05
)
)
[BBB] => Array
(
[0] => Array
(
[Price] => 246.7200
[Time] => 2013-09-27 14:30:06
)
[1] => Array
(
[Price] => 245.4700
[Time] => 2013-09-27 15:45:05
)
[2] => Array
(
[Price] => 244.8300
[Time] => 2013-09-27 17:45:05
)
)
[CCC] => Array
(
[0] => Array
(
[Price] => 189.0900
[Time] => 2013-09-27 14:30:06
)
[1] => Array
(
[Price] => 188.9800
[Time] => 2013-09-27 15:45:05
)
[2] => Array
(
[Price] => 188.8900
[Time] => 2013-09-27 17:45:05
)
)
[DDD] => Array
(
[0] => Array
(
[Price] => 134.3100
[Time] => 2013-10-06 13:30:06
)
[1] => Array
(
[Price] => 134.3100
[Time] => 2013-10-06 13:30:06
)
[2] => Array
(
[Price] => 134.3100
[Time] => 2013-10-06 13:30:06
)
)
)
As you can see company AAA, BBB and CCC all have different Prices and Times in each of their arrays, but company DDD has the same value repeated 3 times (the last value in the database) when the values should be different in the same way as the other companies.
Now from what I have read I am doing this wrong, instead of using foreach I should use implode() on the array and use that, but its confusing me since I can not find a good example where it is used on the FROM field (seems to only be used on WHERE)
My question would be, how can I get away from using a foreach loop since it seems to be causing issues, and use the proper implode() method on the FROM field?
I am guessing I need to modify my while loop also so that the output remains in the same format.
I have started working with Magento, and I'm trying to get all custom options associated with a given product.
I've found a solution to that, however, I ran into issues.
My PHP-code:
foreach ($_product->getOptions() as $optionInfo) :
$values = $optionInfo->getValues();
foreach ($values as $values) :
$valuesArray[$values['option_type_id']] = array("option_type_id" => $values['option_type_id'], "option_id" => $values['option_id'], "title" => $values['title']);
endforeach;
$option = array("id" => $optionInfo->getId(), "type" => $optionInfo->getType(), "title" => $optionInfo->getTitle(), "values" => $valuesArray);
$options[$optionInfo->getId()]= $option;
endforeach;
It sure do return the correct information. Atleast in the first iteration:
[2] => Array
(
[id] => 2
[type] => drop_down
[title] => Custom option 1
[values] => Array
(
[4] => Array
(
[option_type_id] => 4
[option_id] => 2
[title] => Flaphack 1
)
[5] => Array
(
[option_type_id] => 5
[option_id] => 2
[title] => Flaphack 2
)
[6] => Array
(
[option_type_id] => 6
[option_id] => 2
[title] => Flaphack 3
)
)
)
However, during the second iteration (and perhaps even the third and forth and so on), I'm having duplicates of the values. In the second iteration, I'm getting the same values as i got in the first iteration PLUS the correct values for the second iteration:
[1] => Array
(
[id] => 1
[type] => drop_down
[title] => Custom option 2
[values] => Array
(
[4] => Array
(
[option_type_id] => 4
[option_id] => 2
[title] => Flaphack 1
)
[5] => Array
(
[option_type_id] => 5
[option_id] => 2
[title] => Flaphack 2
)
[6] => Array
(
[option_type_id] => 6
[option_id] => 2
[title] => Flaphack 3
)
[1] => Array
(
[option_type_id] => 1
[option_id] => 1
[title] => Flaphack 1.1
)
[2] => Array
(
[option_type_id] => 2
[option_id] => 1
[title] => Flaphack 1.2
)
[3] => Array
(
[option_type_id] => 3
[option_id] => 1
[title] => Flaphack 1.3
)
)
)
Do you guys have any idea what's going on? Would be greatly appriciated.
Best,
Nikolaj
Try this code,
foreach ($_product->getOptions() as $optionInfo) :
$values = $optionInfo->getValues();
$valuesArray = array(); // added line
foreach ($values as $values) :
$valuesArray[$values['option_type_id']] = array("option_type_id" => $values['option_type_id'], "option_id" => $values['option_id'], "title" => $values['title']);
endforeach;
$option = array("id" => $optionInfo->getId(), "type" => $optionInfo->getType(), "title" => $optionInfo->getTitle(), "values" => $valuesArray);
$options[$optionInfo->getId()]= $option;
endforeach;
The $valuesArray is getting values in each iteration and you never cleared it. So when the outer foreach gets into second loop the $valuesArray gets values in incremental fashion. If you clear $valuesArray in each iteration of outer foreach you will get what you wanted.