I have faced a problem during get unique value in foreach loop.
Following is my array.
Array
(
[20] => Array
(
[0] => Array
(
[id] => 4
[category_title] => Specialist Range
[parent] => 20
[front_active] => 1
[category_date] => 2019-05-21 04:04:17
)
[1] => Array
(
[id] => 4
[category_title] => Specialist Range
[parent] => 20
[front_active] => 1
[category_date] => 2019-05-21 04:04:17
)
[2] => Array
(
[id] => 4
[category_title] => Specialist Range
[parent] => 20
[front_active] => 1
[category_date] => 2019-05-21 04:04:17
)
[3] => Array
(
[id] => 6
[category_title] => Cater Foil Rolls
[parent] => 20
[front_active] => 1
[category_date] => 2019-05-21 04:04:24
)
)
[21] => Array
(
[8] => Array
(
[id] => 24
[category_title] => Specialist Range
[parent] => 21
[front_active] => 1
[category_date] => 2019-05-21 04:07:59
)
[9] => Array
(
[id] => 24
[category_title] => Specialist Range
[parent] => 21
[front_active] => 1
[category_date] => 2019-05-21 04:07:59
)
)
)
I written following script for getting unique value in loop
$catArray = array();
foreach($catagory_list as $key=>$catagory){
$catArray[$catagory['parent']][$key] = $catagory;
}
ksort($catArray, SORT_NUMERIC);
foreach ($catArray as $key => $value) {
if($key == 20 ){
$catName ='local';
}elseif ($key == 21) {
$catName ='interstate';
}elseif ($key == 22) {
$catName ='wholesale';
}elseif ($key == 23) {
$catName ='tst';
}
//echo $key;
foreach(array_unique($value) as $keys => $valuess){
echo $valuess['category_title'];
?>
<tr class="table_header">
<th><?php echo $catName." - ".$valuess['category_title'];?> </th>
</tr>
<?php
}
}
Problem is 20 has 4 category_title but when i used array_unique Cater Foil Rolls category title of first parent array is not display.
Output only display
Specialist Range not showing (Cater Foil Rolls)
If you are trying to find unique records in this nested array, then I would key your associative array off of the value of "id". If you are only trying to find unique category_title, then I would key off the value of "category_title". In any case I would use the associate array functionality to ensure uniqueness on whatever key you choose. Then you can apply sorting, etc. on the result.
// find first unique records
$result = [];
foreach($parents as $key1=>$child1) {
foreach($child1 as $key2=>$child2) {
if(!isset($result[$child2['id']])) {
$result[$child2['id']] = $child2;
}
}
}
// result = # => record
OR:
// find first unique categories
$result = [];
foreach($parents as $key1=>$child1) {
foreach($child1 as $key2=>$child2) {
if(!isset($result[$child2['category_title']])) {
$result[$child2['category_title']] = $child2;
}
}
}
// result = category => record
I'm not convinced that array_unique works on multi-dimensional arrays.
See this question.
Related
I need to make my array better.
I am getting data from database and i have milestones and milestone_parts. i want two-dimensional array. I need data of milestones in the first dimension and milestone_parts in the second dimension.
With this code:
$query = "
SELECT
a.id AS `milestone_id`,
a.titel AS `milestone_titel`,
a.client AS `client`,
a.verkocht_id AS `milestone_verkocht_id`,
b.id AS `milestonefase_id`,
b.titel AS `milestonefase_titel`,
b.milestone_id AS `milestonefase_milestone_id`,
b.omschrijving AS `milestonefase_omschrijving`
FROM `milestones` a
INNER JOIN `milestone_parts` b ON a.id=b.milestone_id
WHERE a.verkocht_id = '99'
";
$result= $db->query($dbh, $query);
while ($row = $db->fetchassoc($result))
{
$stone = array($row['milestone_verkocht_id'], $row['milestone_id'], $row['milestone_titel'], $row['client']);
$fase = array($row['milestonefase_milestone_id'],$row['milestonefase_id'],$row['milestonefase_titel']);
$stone[] = $fase;
echo '<pre>'; print_r($stone); echo '</pre>';
}
I get this as result
Array
(
[0] => 99
[1] => 6
[2] => string
[3] => string
[4] => Array
(
[0] => 6
[1] => 10
[2] => string
)
)
Array
(
[0] => 99
[1] => 6
[2] => string
[3] => string
[4] => Array
(
[0] => 6
[1] => 11
[2] => string
)
)
but I need (with names) this:
Array
(
[milestone_verkocht_id] => 99 // This is project id
[milestone_id] => 6
[milestone_title] => string
[client] => string
[10] => Array
(
[milestonefase_milestone_id] => 6
[milestonefase_id] => 10
[milestone_title] => string
)
[11] => Array
(
[milestonefase_milestone_id] => 6
[milestonefase_id] => 11
[milestone_title] => string
)
[12] => Array
(
[milestonefase_milestone_id] => 6
[milestonefase_id] => 12
[milestone_title] => string
)
)
Can you help me or do you have a solution? Help me please!
you can cycle each field returned by the query, checking the field name and making new arrays
$stones = array();
while ($row = $db->fetchassoc($result)) {
$fase = array();
$stone = array('milestones' => array());
foreach ($row as $k => $v) {
if (strpos($k, 'milestonefase_') === 0) {
$fase[$k] = $v;
} else {
$stone[$k] = $v;
}
}
if(!isset($stones[$stone['milestone_id']])) {
$stones[$stone['milestone_id']] = $stone;
}
$stones[$stone['milestone_id']]['milestones'][$fase['milestonefase_id']] = $fase;
}
echo '<pre>'.print_r($stones, true).'</pre>';
Edit
made some changes in order to match the request. Now we use $stones to store the information we already have on a milestone, adding to it the different "$fase" returned from the query
Probably a more clean way is to retrieve all the information with two different queries one for milestones and the other for the fases
Edit2
Added a sub-array for the milestone fases
I have the following array data:
[0] => stdClass Object
(
[schoolBin] => 110140014570
[schoolName] => школа-лицей № 66
[users] => 30
[tb0306_tb0301_id] => 514725
[tb0306_tb3002_id] => 17
[tb0306_countOfCorrectAnswers] => 14
[point] => 4
)
[1] => stdClass Object
(
[schoolBin] => 110140014570
[schoolName] => школа-лицей № 66
[users] => 30
[tb0306_tb0301_id] => 514725
[tb0306_tb3002_id] => 18
[tb0306_countOfCorrectAnswers] => 11
[point] => 4
)
So, i have many tb0306_tb0301_id from one schoolBin, and tb0306_tb0301_id has many tb0306_countOfCorrectAnswers of tb0306_tb3002_id. So i need to sum all tb0306_countOfCorrectAnswers of for all tb0306_tb0301_id of one schoolBin and i have many schoolBin, so i need to do the process for all schoolBin.
Tried the code:
$results = array();
foreach ($schoolResults as $schoolResult) {
$schoolBin = $schoolResult->schoolBin;
if (isset($results[$schoolBin])) {
$results[$schoolBin][] = $schoolResult;
} else {
$results[$schoolBin] = array($schoolResult);
}
}
But could not sum tb0306_countOfCorrectAnswers for one tb0306_tb0301_id.
Any helps guys!
here is the code to sum the tb0306_countOfCorrectAnswers for tb0306_tb0301_id of schoolBin. I use # to ingnore the worning for uninitial value.
$results = array();
foreach ($schoolResults as $schoolResult) {
#$result[$schoolResult->schoolBin][$schoolResult->tb0306_tb0301_id] += $schoolResult->tb0306_countOfCorrectAnswers
}
I'm trying to use the foreach loop to loop over multiple arrays and separate values into 2 groups determined by an ID value on each array and then echo them, eventually to a table.
So for example I have the given 2D array as follows: (I have used just 3 as an example but there will be more in reality)
Array
(
[results] => Array
(
[numbpeople] => 3
[people] => Array
(
[0] => Array
(
[name] => bert
[mainId] => 2
[beens] => 0
[coins] => 8
[total] => 3
[ammount] => 2
[place] => 15
[type] => 0
)
[1] => Array
(
[name] => bungle
[mainId] => 1
[beens] => 0
[coins] => 4
[total] => 0
[ammount] => 10
[place] => 13
[type] => 0
)
[2] => Array
(
[name] => fred
[mainId] => 2
[beens] => 0
[coins] => 3
[total] => 1
[ammount] => 8
[place] => 11
[type] => 0
)
)
)
)
I try the following code but it does not work the way its intended.
//foreach ($data['results']['people'] as $pValue) {
foreach ($data['results']['people'] as $Key => $pValue) {
$numPeople = $data["results"]["numbpeople"]; //[$i];
if($numPeople>-1)
{
$MainId1="";
$MainId2="";
// set up header
echo "<strong>People:<br>name, beens, coins, total.</strong><br>";
echo "<br>";
// calculate who's got what?
$i=0;
while($i<$numPeople)
{
$pname[$i]=$pValue["name"][$i];
$pmainId[$i]=$pValue["mainId"][$i];
$pbeens[$i]=$pValue["beens"][$i];
$pcoins[$i]=$pValue["coins"][$i];
$ptotal[$i]=$pValue["total"][$i];
if(!stristr($pValue["mainId"],"1") && !stristr($pValue["mainId"],"2")) {
if($pmainId[$i]!=$MainId1 && $MainId1=="") {
$p1Name=$pname[$i]; // people1 name
$p1Beens=$pbeens[$i]; // people1 beens
$p1Coins=$pcoins[$i]; // people1 coins
$p1Total=$ptotal[$i]; // people1 total
}
if($pmainId[$i]!=$MainId1 && $MainId1!="" && $MainId2=="") {
$p2Name=$pname[$i]; // people2 name
$p2Beens=$pbeens[$i]; // people2 beens
$p2Coins=$pcoins[$i]; // people2 coins
$p2Total=$ptotal[$i]; // people2 total
}
// Id
if($pmainId[$i]!=$MainId1 && $MainId1=="") {
$MainId1=$pmainId[$i];
}
if($pmainId[$i]!=$MainId1 && $MainId1!="" && $MainId2=="") {
$MainId2=$pmainId[$i];
}
} else {
$MainId1="1";
$MainId2="2";
}
// output people ?
echo $i.". -> ".$p1Name[$i].", ".$p1Beens[$i].", ".$p1Coins[$i].", ".$p1Total[$i];
// 1 bungle 0 4 0
echo "<br>";
echo $i.". -> ".$p2Name[$i].", ".$p2Beens[$i].", ".$p2Coins[$i].", ".$p2Total[$i];
// 1 bert 0 8 3
// 2 fred 0 3 1
echo "<br>";
echo $MainId1, $MainId2;
// 1 2
echo "<br>";
$i++;
}
}else {
echo "No people";
}
}
A better more refined solution would be very helpful.
Some advices after looking on code:
Prepare data before sending it to view
Next try to separate logic from view
My answer shows how array can be separeted in arrays by id:
$people=$results["results"]["people"];
$result=[];
$count=count($people);// i don't need special numbpeople in array
for ($i=0; $i<$count; $i++){
$id=$people[$i]['mainId'];
if (!isset($result[$id]))
$result[$id]=[];//create new array for this id
$result[$id][]=$people[$i]; //add people to this collection
}
After above loop in results we have this structure:
[
1 => [ [peopley],[peoplex] ]
2 => [ [peoplez],[peoplew] ]
....
]
This structure is grouped by mainId.
How to show people from above structure:
$size=count($result)
for ($i=0;$i<$size; $i++){
//loop on groups
$peoples=$result[$i];//array with people in this group
$groupSize=count($peoples);
for ($j=0;$j<$groupSize; $j++){
//loop in group
echo $peoples[$j]["name"];//example show name
}
}
I have the following table:
And I use this function to get data from it:
function get_cart_by($player_id)
{
global $db;
$sql = 'SELECT DISTINCT(item_id) FROM ' . PCP_MARKET_CART . '
WHERE player_id = ' . (int) $player_id;
$result = $db->sql_query($sql);
$rowset = $db->sql_fetchrowseT($result);
$db->sql_freeresult($result);
$cart = array();
foreach ($rowset as $item)
{
$cart[] = $item['item_id'];
}
return $cart;
}
The result looks like this:
Array
(
[0] => 16
[1] => 17
[2] => 49
[3] => 48
[4] => 18
[5] => 19
[6] => 51
)
Now I have an array that lists all my products from another table without looking at the player_id. I want to use the array demonstrated above and add a custom class to the items that do not use the player_id, like show which items the user already has on cart.
The other array that lists all the products looks like this:
Array
(
[0] => Array
(
[item_id] => 16
[parent_id] => 11
[cat_position] => 0
[item_position] => 1
[item_type] => product
[item_title] => Custom Business
[item_description] => Some description
[item_price] => 9.99
[item_units] => 500
[item_preview] => http://i.imgur.com/3eCpMMm.png
[times_sold] => 0
[daopay_url] => http://i.imgur.com/QA7bBfJ.jpg
[public] => 1
[time] => 1384709635
)
[1] => Array
(
[item_id] => 17
[parent_id] => 11
[cat_position] => 0
[item_position] => 1
[item_type] => product
[item_title] => Custom Business
[item_description] => Some description
[item_price] => 9.99
[item_units] => 500
[item_preview] => http://i.imgur.com/3eCpMMm.png
[times_sold] => 0
[daopay_url] => http://i.imgur.com/QA7bBfJ.jpg
[public] => 1
[time] => 1384709635
)
[2] => Array
(
[item_id] => 49
[parent_id] => 11
[cat_position] => 0
[item_position] => 1
[item_type] => product
[item_title] => Custom Business
[item_description] => Some description
[item_price] => 9.99
[item_units] => 500
[item_preview] => http://i.imgur.com/3eCpMMm.png
[times_sold] => 0
[daopay_url] => http://i.imgur.com/QA7bBfJ.jpg
[public] => 1
[time] => 1384709635
)
)
Now based on the first array, I want to mark the same item IDs on the second arrays and show that they are different (on cart).
I have tried quite a lot and for some reason, I managed to mark only item_id 16 and 17, the rest are not getting "marked" for some reason.
This is the code I used:
$cartar = $market->get_cart_by($user->data['player_id']);
$cartln = sizeof($cartar) - 1;
// Fetch items of the selected category
$items = $market->fetch_cat_items($cat_id); // Equivalent to the array above
$index = 0;
print_r($items);
foreach ($items as $item)
{
$name = $item['item_name'];
if ($cartln >= $index)
{
if ($cartar[$index] == $item['item_id'])
$name .= $cartar[$index];
}
echo $name;
$index++;
}
I tried to make the example explain my case the best way possible. So, when I echo out $name it only outputs thename16 and thename17 (those two), but it doesn't continue to 49 and so on.
Please be aware that the array with all the products in it is quite large, I made it shorter for demonstration purposes only.
Were am I failing in my code? Why are only the first two items getting "marked"? I'm quite in a hurry right now, once I get back from a meeting I'll try to explain my issue further.
i don't know if i understood correctly but maybe you want to do it like this:
foreach ($items as $item) {
$name = $item['item_name'];
if(in_array($item['item_id'],$cartar)) {
$name .= $item['item_id'];
}
echo $name;
}
used in_array() to check if the item_id exists somewhere in $cartar. No matter on which position in array.
I have a codeigniter shopping cart going and its "cart" array is the following:
Array (
[a87ff679a2f3e71d9181a67b7542122c] => Array
(
[rowid] => a87ff679a2f3e71d9181a67b7542122c
[id] => 4
[qty] => 1
[price] => 12.95
[name] => Maroon Choir Stole
[image] => 2353463627maroon_3.jpg
[custprod] => 0
[subtotal] => 12.95
)
[8f14e45fceea167a5a36dedd4bea2543] => Array
(
[rowid] => 8f14e45fceea167a5a36dedd4bea2543
[id] => 7
[qty] => 1
[price] => 12.95
[name] => Shiny Red Choir Stole
[image] => 2899638984red_vstole_1.jpg
[custprod] => 0
[subtotal] => 12.95
)
[eccbc87e4b5ce2fe28308fd9f2a7baf3] => Array
(
[rowid] => eccbc87e4b5ce2fe28308fd9f2a7baf3
[id] => 3
[qty] => 1
[price] => 14.95
[name] => Royal Blue Choir Stole
[image] => 1270984005royal_vstole.jpg
[custprod] => 1
[subtotal] => 14.95
)
)
My goal is to loop through this multidimensional array some how and if ANY product with the key value pair "custprod == 1" exists, then my checkout page will display one thing, and if no custom products are in the cart it displays another thing. Any help is appreciated. Thanks.
Rather than looping over it, you can check for the custprod key using array_key_exists. Or simply check to see if arr['custprod'] isset (both functions handle null differently).
$key = "custprod";
$arr = Array(
"custprod" => 1,
"someprop" => 23
);
if (array_key_exists($key, $arr) && 1 == $arr[$key]) {
// 'custprod' exists and is 1
}
function item_exists($cart, $custprod) {
foreach($cart as $item) {
if(array_key_exists("custprod", $item) && $item["custprod"] == $custprod) {
return true;
}
}
return false;
}
Now, you can use this function to check if product exist in stack:
if(item_exists($cart, 1)) {
// true
} else {
// false
}
You still need to loop the array to check it:
$cust_prod_found = false;
foreach($this->cart->contents() as $item){
if (array_key_exists("custprod", $item) && 1 == $item["custprod"]) {
$cust_prod_found = true; break;
}
}
if ($cust_prod_found) {
// display one thing
} else {
// display another thing
}