I have a PHP loop that is pushing data into an array that will eventually be used to create a list of select options in my dropdown.
I feel like it is kinda close but I am doing something wrong somewhere.
The array of types needs to be part of the category it is associated with.
// Get the list of behavior types
public function _behavior_types()
{
$cat = $this->global_model->get_behavior_categories();
$typ = $this->global_model->get_behavior_types();
$output = array();
// Loop over our categories
foreach($cat as $c)
{
// Push the category name to an array
$output[] = $c['categoryName'];
// Loop over our types
foreach($typ as $t)
{
// If this type belongs to the category we are currently in, add it to the array
if($t['categoryID'] == $c['categoryID'])
{
array_push($output, $t);
}
}
}
return $output;
}
I have something out of place however and its causing the array to not be set up in the correct way.
Here is the current output:
Array
(
[0] => Negative
[1] => Array
(
[categoryID] => 2
[points] => -3
[typeID] => 4
[typeName] => Bad School Day
)
[2] => Positive
[3] => Array
(
[categoryID] => 1
[points] => 2
[typeID] => 1
[typeName] => Ate Dinner
)
[4] => Array
(
[categoryID] => 1
[points] => 2
[typeID] => 3
[typeName] => Brushed Teeth
)
[5] => Array
(
[categoryID] => 1
[points] => 3
[typeID] => 2
[typeName] => Completed Homework
)
)
Here is my desired output:
Array
(
[0] => Negative
[0] => Array
(
[categoryID] => 2
[points] => -3
[typeID] => 4
[typeName] => Bad School Day
)
[1] => Positive
[0] => Array
(
[categoryID] => 1
[points] => 2
[typeID] => 1
[typeName] => Ate Dinner
)
[1] => Array
(
[categoryID] => 1
[points] => 2
[typeID] => 3
[typeName] => Brushed Teeth
)
[2] => Array
(
[categoryID] => 1
[points] => 3
[typeID] => 2
[typeName] => Completed Homework
)
)
The dropdown in turn will look like:
Negative
Bad day at school
Positive
Ate Dinner
Brushed Teeth
Completed Homework
Your desired output is not really a valid array structure, at least how you have it typed. $output[0] cannot be both a string Negative and an array of options. I suggest making the category the key something like this:
// Get the list of behavior types
public function _behavior_types()
{
$cat = $this->global_model->get_behavior_categories();
$typ = $this->global_model->get_behavior_types();
$output = array();
// Loop over our categories
foreach($cat as $c)
{
// Push the category name to an array
$output[$c['categoryName']] = array();
// Loop over our types
foreach($typ as $t)
{
// If this type belongs to the category we are currently in, add it to the array
if($t['categoryID'] == $c['categoryID'])
{
array_push($output[$c['categoryName']], $t);
}
}
}
return $output;
}
Related
I have an array that contains 3 products with attributes of "color" and "size" and the products are identified by a number ( ['code'] ).
My problem is that when i pull the data from the database I get this array that is in 6 pieces because "color" and "size" get stored in separate arrays.
My question is, how do I generate the data into an array of these 3 products with all their data in the same array.
Array(
[0] => Array
(
[code] => 123
[name] => box
[stock] => 2.00
[price] => 10.00
[color] => brown
)
[1] => Array
(
[code] => 123
[name] => box
[stock] => 2.00
[price] => 10.00
[size] => L
)
[2] => Array
(
[code] => 1234
[name] => box
[stock] => 3.00
[price] => 11.00
[color] => brown
)
[3] => Array
(
[code] => 1234
[name] => box
[stock] => 3.00
[price] => 11.00
[size] => XL
)
[4] => Array
(
[code] => 12345
[name] => box
[stock] => 4.00
[price] => 12.00
[size] => XL
)
[5] => Array
(
[code] => 12345
[name] => box
[stock] => 4.00
[price] => 12.00
[color] => gray
)
)
Expected output:
[0] => Array
(
[code] => 123
[name] => box
[stock] => 4.00
[price] => 12.00
[color] => gray
[size] => XL
)
What i'm looking to do is just combine the doubled array into one. Dont want to mess with SQL anymore - it gets attribute name in one table, attribute values from another table, code,stock,price from another table, name from another table. I know something can be done with just this array even if it will be just a temporary solution.
You can do this:
assuming your array is $products
$merged = array();
foreach($products as $product) {
if (!isset($sorted[$product['code']])) {
$merged[$product['code']] = $product;
} else {
$merged[$product['code']] = array_merge($sorted[$product['code']], $product);
}
}
Use the product code as array key and then merge the array.
If the two rows are always direct successors, with the first one holding the color field, while the latter holes the size field, you can make it easily by iterating over them in a for loop:
$maxCount = count($array);
for ($i = 1; $i < $maxCount; $i += 2) {
$array[$i - 1]['size'] = $array[$i]['size'];
unset($array[i]);
}
This will iterate over each second element of the array and add the size field to the preceding field.
If you need to have succeeding array keys afterwards you can call $arry = array_values($array);.
In case the the associated rows might not be successors you need to map them based on their code field (in case thats the primary key). You can use array_reduce() for that:
$desiredOutput = array_reduce($array, function($output, $element) {
if (!array_key_exists($element['code'], $output)) {
$output[$element['code']] = $element;
} elseif (array_key_exists('size', $element)) {
$output[$element['code']]['size'] = $element['size'];
} elseif (array_key_exists('color', $element)) {
$output[$element['code']]['color'] = $element['color'];
}
return $output;
}, []);
I've got an array and I need count the keys with a specific value, which is proving to be a nightmare.
Array([0] => Array
(
[0] => 1
[ruleid] => 1
[1] => Test Outbound Life 1
[rule_name] => Test Outbound Life 1
[2] => Life Insurance
[product_type] => Life Insurance
[3] => 1
[status] => 1
[4] => 1000
[priority] => 1000
[5] => 100
[quantity] => 100
[6] => 1-2-3-4-5-6-7-
[dayofweek] => 1-2-3-4-5-6-7-
[7] => 2
[income] => 2
[8] => external/arc.php
[integrationfile] => external/arc.php
[9] => 1
[partnerid] => 1
)
[1] => Array
(
[0] => 2
[ruleid] => 2
[1] => Test Outbound Life 2
[rule_name] => Test Outbound Life 2
[2] => Life Insurance
[product_type] => Life Insurance
[3] => 1
[status] => 1
[4] => 800
[priority] => 800
[5] => 100
[quantity] => 100
[6] => 1-2-3-4-5-6-7-
[dayofweek] => 1-2-3-4-5-6-7-
[7] => 2
[income] => 2
[8] => test.php
[integrationfile] => test.php
[9] => 1
[partnerid] => 1
) )
The array will be generated dynamically so the same array will appear in the array.
I want to count how many times the same ruleid appears is it will look like this:
Array{
[1] => 1
[2] => 1
}
Update: I need to count how many times ruleid = 2 or how many times ruleid = 1
So you want to count the number of time each ruleid appears inside an array.
Let's call this array $count. This is how I'd do it.
$count = array();
foreach($arrays as $array) { // $arrays is your big ass array containing arrays
// increment the value with the key corresponding to ruleid (improved by JustOnUnderMillions)
$count[$array['ruleid']] = isset($count[$array['ruleid']]) ? ($count[$array['ruleid']] + 1) : 1;
}
print_r(count); // should give you what you're looking for
I have worked it out by looping and counting how many times a ruleid appears in an array.
foreach ($count as $key => $value) {
$c = 0;
//check that outbound has passed all rules
foreach ($out as $k => $v) {
if ($v['ruleid']==$key) {
$c +=1;
}
}
if ($c==$value) {
//add valid outbound to array
foreach ($out as $k => $v) {
if ($v['ruleid']==$key) {
$valid[$key] = $v;
}
}
}
}
The loop checks the ruleid has passed all rules I had already counted in the $count variable.
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>';
}
}
Is there a way to foreach() through one array based on a matching value with a different key in another array? In this example, I have a category array ($cat_data) with cat_id as a key and an image array ($img_data) with category_id as a key.
Array (
[0] => Array (
[cat_id] => 1
[cat_name] => Category 1
)
[1] => Array (
[cat_id] => 2
[cat_name] => Category 2
)
)
Array (
[0] => Array (
[img_id] => 2
[img_name] => demo1.jpg
[img_label] => Demo 1
[category_id] => 2
[img_order] => 1
)
[1] => Array (
[img_id] => 3
[img_name] => demo2.jpg
[img_label] => Demo 2
[category_id] => 2
[img_order] => 2
)
[2] => Array (
[img_id] => 4
[img_name] => demo3.jpg
[img_label] => Demo 3
[category_id] => 1
[img_order] => 1
)
)
What I want is to output my display so it looks like the following:
Category 1
demo3.jpg
Category 2
demo1.jpg
demo2.jpg
Since I'm really not great at fully grasping arrays, I thought I'd try Stack, and I haven't been able to find an answer to my question, partially because I'm not sure what to ask for precisely. Any help??
The naïve way:
foreach ($cat_data as $cat) {
echo $cat['cat_name'];
foreach ($img_data as $img) {
if ($img['category_id'] != $cat['cat_id']) {
continue;
}
echo $img['img_name'];
}
}
This is rather inefficient, since it loops through the $imgs array several times, but easy and works.
More efficient:
$images = array();
foreach ($img_data as $img) {
$images[$img['category_id']][] = $img;
}
foreach ($cat_data as $cat) {
echo $cat['cat_name'];
if (isset($images[$cat['cat_id']])) {
foreach ($images[$cat['cat_id']] as $img) {
echo $img['img_name'];
}
}
}
This first groups all images by category into a new array, which you can then loop over directly once.
I would urge you to redesign your array when you fill them with data to instead look something like this.
Array (
[0] => Array (
[cat_id] => 1
[cat_name] => Category 1
[images] = Array(
[0] => Array (
[img_id] => 4
[img_name] => demo3.jpg
[img_label] => Demo 3
[category_id] => 1
[img_order] => 1
)
)
)
[1] => Array (
[cat_id] => 2
[cat_name] => Category 2
[images] = Array(
[0] => Array (
[img_id] => 4
[img_name] => demo3.jpg
[img_label] => Demo 3
[category_id] => 1
[img_order] => 1
)
[1] => Array (
[img_id] => 2
[img_name] => demo1.jpg
[img_label] => Demo 1
[category_id] => 2
[img_order] => 1
)
)
)
)
Then you would have all the relational data connected and would just have to loop through your array of categories and print the images associated with each one in turn. The numbered indexes could even be changed to associative names if the id of the catagory weren't important for example. Then the array could be indexed with the name of the category and just contain the images of that category.
If the images are to be used in other places where you initial layout of those fits better you could still use this layout for your main data graph. Just replace the actual data of the images in the images array under each category with a reference to the actual image object.