Unxpected result when iterating nested arrays for merging content in PHP - php

I have 2 nested arrays over which I intent to iterate over one and insert into it a portion of a match in the other based on a key->value.
The idea is to iterate for each element of arrayA and nested iterate for each key->value of arrayB. When arrayA element equals to arrayB key->value i want to insert into arrayB a key->value of arrayA.
The problem I am having is that for some reason in the loop of arrayB it should iterate 78 times but is doing it only 2.
I know there is something messed up with the iterations but can't pin point.
Here is a sample of arrayA, arrayB and my code.
arrayA
arrayB
Here is my code
foreach($premiumContent as $prem_key => $targets)
{
$totCat = 0;
foreach($result as $category) //(result = 2 shop, ff) (category shop.designers, ff.restaurant)
{
$totCat = $totCat + 1;
$totFeatures = 0;
foreach($category as $features) //features = 1 designers, restaurants
{
$totFeatures = $totFeatures + 1;
//*********HERE IS THE PROBLEM IS NOT ITERATING BY THE LIST OF ALL FEATURES
$totFeature = 0;
foreach ($features as $feature) //stores
{
$totFeature = $totFeature + 1;
$properties = $feature[0]->properties;
if ($feature[0]->id == $prem_key)
{
if(count($targets[media]) > 0)
{
$properties->media = $targets[media];
}
else
{
$properties->media = '';
}
if(count($targets[offer]) > 0)
{
$properties->offer = $targets[offer];
}
else
{
$properties->offer = '';
}
if(count($targets[bi]) > 0)
{
$properties->bi = $targets[bi];
}
else
{
$properties->bi = '';
}
if(count($targets[info]) > 0)
{
$properties->info = $targets[info];
}
else
{
$properties->info = '';
}
}
}
}
}
}
return $result;
Could someone explain me what am I doing wrong? I am sure there is a better approach to this.
Here is the fix.
foreach($result as $category) //(result = 2 shop, ff) (category shop.designers, ff.restaurant)
{
$name = $category->dispName;
//echo $name;
foreach($category->list as $features) //features = 1 designers, restaurants
{
foreach ($features as $featureKey => $featureVal) //stores
{
$properties = $featureVal->properties;
if ($featureVal->id == $prem_key)
{
if(count($targets[media]) > 0)
{
$properties->media = $targets[media];
}
else
{
$properties->media = '';
}
if(count($targets[offer]) > 0)
{
$properties->offer = $targets[offer];
}
else
{
$properties->offer = '';
}
if(count($targets[bi]) > 0)
{
$properties->bi = $targets[bi];
}
else
{
$properties->bi = '';
}
if(count($targets[info]) > 0)
{
$properties->info = $targets[info];
}
else
{
$properties->info = '';
}
}
}
}
}
}

Related

Assign the same rank to student with the same scores

I'm assigning ranks to students based on their scores but I encountered a problem where if two or more students have the same scores they are given different ranks.
E.G John, Rita, and Mary scored 76. John is 1st, Rita is 2nd, and Mary is 3rd.
John ==> 76
Rita ==> 76
Mary ==> 76
Bukky ==>74
I want three of them to have the rank as 1st.
John ==> 76
Rita ==> 76
Mary ==> 76
Bukky ==>74
public function getStudentpositionOnlyClass($student_id, $class_id, $terms)
{
$array_product = array();
if ($class_id == 22 || $class_id == 23) {
if ($terms == 'f') {
$totField = 'ft_tot_score';
$table = 'ftscores_rn';
} elseif ($terms == 'm') {
$totField = 'mt_tot_score';
$table = 'mtscores_rn';
} elseif ($terms == 's') {
$totField = 'tot_score';
$table = 'scores_rn';
} elseif ($terms == 'h') {
$totField = 'h_tot_score';
$table = 'hscores_rn';
}
} else {
if ($terms == 'f') {
$totField = 'ft_tot_score';
$table = 'ftscores_primary';
} elseif ($terms == 'm') {
$totField = 'mt_tot_score';
$table = 'mtscores_primary';
} elseif ($terms == 's') {
$totField = 'tot_score';
$table = 'scores_primary';
} elseif ($terms == 'h') {
$totField = 'h_tot_score';
$table = 'hscores_primary';
}
}
$fail = 0;
$pass = 0;
$resultlist = $this->student_model->fullSearchByClass($class_id);
foreach ($resultlist->result_array() as $key => $stdName) {
$idd = $key + 1;
$mId[$idd] = $stdName['pstudent_id'];
$totalSubMarks = $this->db->query(
"SELECT mts.subject_id
FROM " . $table . " mts
LEFT JOIN subjects sub ON(sub.id=mts.subject_id)
WHERE class_id=" . $class_id .
" AND mts.subject_id IS NOT NULL
GROUP BY mts.subject_id ORDER BY sub.name");
$gtotal = 0;
$totSubjects = 0;
foreach ($totalSubMarks->result_array() as $tmrow) {
$totalMarks = $this->student_model->getTotalMarksForStudnets($tmrow['subject_id'],
$stdName['pstudent_id'], $table, $totField);
// //// set mtotalmark
$gtotal = $gtotal + $totalMarks;
// //// set mgtotal
$mGTotal[$idd] = $gtotal;
if ($totalMarks != 0) {
$totSubjects = $totSubjects + 1;
}
// //// set mAvg
if ($totSubjects != 0) {
$mAvg[$idd] = round($gtotal / $totSubjects, 1);
} else {
$mAvg[$idd] = 0;
}
}
// /////////
if ($totSubjects != 0) {
$percentage = ($gtotal / $totSubjects);
}
if ($percentage >= 0 && $percentage <= 39.99) {
$fail = $fail + 1;
} else {
$pass = $pass + 1;
}
}
foreach ($mAvg as $dd => $val) {
// if pure numbers store in nums array
if (! is_nan($val)) {
$nums[$dd] = $val;
}
}
arsort($nums);
$id = 1;
foreach ($nums as $kk => $av) {
foreach ($totalSubMarks->result_array() as $tmrow) {
$totalMarks = $this->student_model->getTotalMarksForStudnets($tmrow['subject_id'], $mId[$kk], $table,
$totField);
}
if ($student_id == $mId[$kk]) {
return $id;
}
// $array_product['student'.$mId[$kk]]= $id;
$id += 1;
}
}
As mickmackusa stated in his comment you have to memorize the previous score and only increment the rank if the score has changed. As you already order your results we can assume a score change between 2 iterations is always a decrease.
Your variable names are very unintuitive. So maybe my code changes are in the wrong place but you shoud understand the concept. I assume that $totSubjects is that score.
Try not to shorten a variable's name too much because you have no benifit but loose that important information on what it is. At least comment a variable assignment if its unclear what the variable holds of.
Change your loop like this:
$previousScore = null; // added THIS
foreach ($totalSubMarks->result_array() as $tmrow) {
$totalMarks = $this->student_model->getTotalMarksForStudnets($tmrow['subject_id'],
$stdName['pstudent_id'], $table, $totField);
// set mtotalmark
$gtotal = $gtotal + $totalMarks;
// set mgtotal
$mGTotal[$idd] = $gtotal;
if ($totalMarks != 0) {
if($previousScore != $totalMarks) { // added THIS
$totSubjects = $totSubjects + 1;
} else { // added THIS
$totSubjects = $totSubjects; // keep rank without incrementing
}
}
$previousScore = $totalMarks; // added THIS
// set mAvg
if ($totSubjects != 0) {
$mAvg[$idd] = round($gtotal / $totSubjects, 1);
} else {
$mAvg[$idd] = 0;
}
}
In case $gtotal or any of the other mystic variables ;) is holding the score then try to modify my given code changes to $gtotal. Shouldn't be too hard. In that case just add a comment so I can change my answer that it's actualy correct.
Hope that helps!

How to Update Categories that Already Exists in Magento Database Using Custom Script

I have Already Created The Categories in Magento by using the custom script,
but issue is when I again run the same URL my script creates another set of same category. as i want to update the existing category and insert the new categories if exist in the csv.
My csv structure is:
Category 1,Description,Category 2,Description,Category 3,Description,Category 4,Description
1,COSTUMES,1,ADULTS,1,MENS
1,COSTUMES,1,ADULTS,1,MENS,2,ASIAN
1,COSTUMES,1,ADULTS,1,MENS,3,BIKER
1,COSTUMES,1,ADULTS,1,MENS,1,CAPES & ROBES
1,COSTUMES,1,ADULTS,1,MENS,5,CAVE PEOPLE
Thanking All of You in Advance For Your Answer
Below is my code to create multi level categories:
define('MAGENTO', realpath(dirname(__FILE__)));
require_once MAGENTO . '/app/Mage.php';
umask(0);
Mage::app()->setCurrentStore(Mage_Core_Model_App::ADMIN_STORE_ID);
$count = 0;
$file = fopen('export/web categories.csv', 'r');
function odd($var)
{
$odd = array();
foreach ($var as $k => $v) {
if ($k % 2 !== 0) {
$odd[$k] = $v;
}
}
return $odd;
}
function even($var)
{
$even = array();
foreach ($var as $k => $v) {
if ($k % 2 == 0) {
$even[$k] = $v;
}
}
return $even;
}
function strcount($str,$sy){
$ch= explode($sy, $str);
return count($ch);
}
$pos=0;
$row_config= array();
$test=array();
$catgoryID=array();
$parID = 1;
while (($line = fgetcsv($file)) !== FALSE) {
if(!in_array($valtest,$row_config)){
if($count == 0){
$count++;
continue;
}
$count++;
$filterd_data=array_filter($line);
$odd_cell_data=odd($filterd_data);
$even_cell_data=even($filterd_data);
$config=array();
$string='';
$intialID=$even_cell_data[0];
foreach($odd_cell_data as $key=>$val){
if(!in_array($val,$config)){
$config[] = $val;
$data['general']['name'] =$val;
$data['general']['meta_title'] = "";
$data['general']['meta_description'] = "";
$data['general']['is_active'] = "";
$data['general']['url_key'] = "";
$data['general']['is_anchor'] = 0;
$data['general']['position'] =1 ;
$storeId = 0;
$string .=$val.'~';
if(!array_key_exists($string, $row_config)){
$catID=createCategory($data, $storeId);
$catgoryID[$string]=$catID;
$row_config[$string]=$parID;
} else {
$parID =$row_config[$string] ;
$row_config[$string]=$row_config[$string];
}
if( strcount($string,'~')==2){
$parID=1;
}
$int[$string]=$parID;
assignCat($catgoryID[$string],$parID);
$parID = $catgoryID[$string];
sleep(0.5);
unset($data);
}
}
}
}
//This Function is used for create each category
function createCategory($data, $storeId) {
$category = Mage::getModel('catalog/category');
$category->setStoreId($storeId);
if (is_array($data)) {
$category->addData($data['general']);
if (!$category->getId()) {
$parentId = $data['category']['parent'];
if (!$parentId) {
if ($storeId) {
$parentId = Mage::app()->getStore($storeId)->getRootCategoryId();
} else {
$parentId = Mage_Catalog_Model_Category::TREE_ROOT_ID;
}
}
$parentCategory = Mage::getModel('catalog/category')->load($parentId);
$category->setPath($parentCategory->getPath());
} if ($useDefaults = $data['use_default']) {
foreach ($useDefaults as $attributeCode) {
$category->setData($attributeCode, null);
}
}
$category->setAttributeSetId($category->getDefaultAttributeSetId());
if (isset($data['category_products']) && !$category->getProductsReadonly()) {
$products = array();
parse_str($data['category_products'], $products);
$category->setPostedProducts($products);
} try {
$category->save();
$category = Mage::getModel('catalog/category')->load($category->getId());
$category->setPosition($data['general']['position']);
$category->addData($data['general']);
$category->save();
echo "Suceeded <br /> ";
} catch (Exception $e) {
echo "Failed <br />";
}
}
return $category->getId();
}
//This Function is used for moving category under respective parent
function assignCat($id, $parent){
$category = Mage::getModel( 'catalog/category' )->load($id);
Mage::unregister('category');
Mage::unregister('current_category');
Mage::register('category', $category);
Mage::register('current_category', $category);
$category->move($parent);
return;
}

getting the even index of a string

hey guys im trying to get the even indexes of a string from the db then save them in a variable then echo. but my codes seems doesnt work. please help. here it is
require_once('DBconnect.php');
$school_id = '1';
$section_id = '39';
$select_pk = "SELECT * FROM section
WHERE school_id = '$school_id'
AND section_id = '$section_id'";
$query = mysql_query($select_pk) or die (mysql_error());
while ($row = mysql_fetch_assoc($query)) {
$public_key = $row['public_key'];
}
if ($public_key) {
$leng_public_key = strlen($public_key);
$priv_key_extract = "";
$array_pki = array();
for ($i=0; $i <=$leng_public_key-1 ; $i++) {
array_push($array_pki,$public_key[$i]);
}
foreach ($array_pki as $key => $value) {
if($key % 2 == 0) {
$priv_key_extract += $public_key[$key];
} else {
$priv_key_extract ="haiiizzz";
}
}
}
echo $priv_key_extract;
as you can see im trying to use modulo 2 to see if the index is even.
I have updated your code as below, it will work now :
<?php
$public_key = 'A0L8V1I5N9';
if ($public_key) {
$leng_public_key = strlen($public_key);
$priv_key_extract = "";
$array_pki = array();
for ($i=0; $i <=$leng_public_key-1 ; $i++) {
array_push($array_pki,$public_key[$i]);
}
foreach ($array_pki as $key => $value) {
//Changed condition below $key % 2 ==0 => replaced with $key % 2 == 1
if($key % 2 == 1) {
// Changed concatenation operator , += replaced with .=
$priv_key_extract .= $public_key[$key];
} /*else {
//Commented this as it is getting overwritten
$priv_key_extract ="haiiizzz";
}*/
}
}
echo $priv_key_extract;
?>
Try this function
function extractKey($key) {
if (empty($key) || !is_string($key)) return '';
$pkey = '';
for ($i=0;$i<strlen($key);$i++) {
if ($i % 2 == 0) {
$pkey .= $key[$i];
}
}
return $pkey;
}
echo extractKey('12345678'); # => 1357

Remove duplicate values on an array with a condition in PHP

I want to remove some duplicate values on an array, but there is a condition that the script has to ignore the array that contains a specific word.
Below code is adapted from PHP: in_array.
$array = array( 'STK0000100001',
'STK0000100002',
'STK0000100001', //--> This should be remove
'STK0000100001-XXXX', //--> This should be ignored
'STK0000100001-XXXX' ); //--> This should be ignored
$ignore_values = array('-XXXX');
if(make_unique($array, $ignore_values) > 0) {
//ERROR HERE
}
The function to make the array unique is:
function make_unique($array, $ignore) {
$i = 0;
while($values = each($array)) {
if(!in_array($values[1], $ignore)) {
$dupes = array_keys($array, $values[1]);
unset($dupes[0]);
foreach($dupes as $rmv) {
$i++;
}
}
}
return $i;
}
I have tried to use if(!in_array(str_split($values[1]), $ignore)) ... but it just the same.
The array should become like:
STK0000100001
STK0000100002
STK0000100001-XXXX
STK0000100001-XXXX
How to do that?
Try this one, just remove the print_r(); inside the function when using in production
if(make_unique($array, $ignore_values) > 0) {
//ERROR HERE
}
function make_unique($array, $ignore) {
$array_hold = $array;
$ignore_val = array();
$i = 0;
foreach($array as $arr) {
foreach($ignore as $ign) {
if(strpos($arr, $ign)) {
array_push( $ignore_val, $arr);
unset($array_hold[$i]);
break;
}
}
$i++;
}
$unique_one = (array_unique($array_hold));
$unique_one = array_merge($unique_one,$ignore_val);
print_r($unique_one);
return count($array) - count($unique_one);
}
This should work for >= PHP 5.3.
$res = array_reduce($array, function ($res, $val) use ($ignore_values) {
$can_ignore = false;
foreach ($ignore_values as $ignore_val) {
if (substr($val, 0 - strlen($ignore_val)) == $ignore_val) {
$can_ignore = true;
break;
}
}
if ( $can_ignore || ! in_array($val, $res)) {
$res[] = $val;
}
return $res;
}, array()
);
Otherwise
$num_of_duplicates = 0;
$res = array();
foreach ($array as $val) {
$can_ignore = false;
foreach ($ignore_values as $ignore_val) {
if (substr($val, 0 - strlen($ignore_val)) == $ignore_val) {
$num_of_duplicates++;
$can_ignore = true;
break;
}
}
if ( $can_ignore || ! in_array($val, $res)) {
$res[] = $val;
}
}
Edit: Added duplicate count to the second snippet.

Why isn't my sorting algorithm working?

I'm developing a system for a client that creates a csv of packing labels which is sent to a printer. The client has six different items. Customers order products in bulk from my client. Two items (product A and product B) share the same packing line. In order to make packing more efficient my client wants to alternate between packing product A and packing product B first.
For example, if John, Sally, and James all ordered both products, the system needs to write John's orders to the csv starting with product A, Sally's orders starting with product B, and James' orders starting with product A again.
I've pasted my non-working code below, but this is really screwing with my head and I'm having a really tough time with it.
foreach($orders as $order) {
$name = null;
$phone = null;
$account = DAO_ContactPerson::get($order->account_id);
$delivery = false;
if($account->is_agency) {
$name = $order->getAttribute('name');
$phone = $order->getAttribute('phone');
} else {
$name = sprintf("%s %s",
$account->getPrimaryAddress()->first_name,
$account->getPrimaryAddress()->last_name
);
$phone = $account->phone;
}
$name = trim($name);
$phone = trim($phone);
$items = $order->getItems();
if($order->getAttribute('delivery')) {
$type = 'deliveries';
$destination = 'Delivery';
$address = sprintf("%s %s %s",
$order->getAttribute('delivery_address.line1'),
$order->getAttribute('delivery_address.line2'),
$order->getAttribute('delivery_address.postal')
);
} else {
$type = 'pickups';
$agency = DAO_ContactPerson::getAgency($order->getAttribute('pickup'));
$destination = $agency->name;
// Override account id so orders are grouped by agency
$order->account_id = $agency->id;
$address = null;
}
// var_dump($order->id);
// Init account array
if(!isset($rows[$type][$order->account_id]))
$rows[$type][$order->account_id] = array('combined' => array(), 'separate' => array());
foreach($items as $item) {
$packing = 'separated';
if($item->product_id == 3 || $item->product_id == 4)
$packing = 'combined';
if(!isset($rows[$type][$order->account_id][$packing][$item->product_id]))
$rows[$type][$order->account_id][$packing][$item->product_id] = array();
$i = 0;
while($i < $item->quantity) {
$rows[$type][$order->account_id][$packing][$item->product_id][] = array(
'number' => $order->id,
'destination' => $destination,
'size' => $item->product_id,
'name' => $name,
'address' => $address,
'phone' => $phone
);
$i++;
}
}
// if($order->id == 176) {
// var_dump($rows[$type][$order->account_id][$packing]);
// }
}
$this->weight = 1;
$pickups = count($rows['pickups']);
for($i = 0; $i < $pickups; $i++) {
$account =& $rows['pickups'][$i];
$account['output'] = array();
if(isset($account['combined'])) {
$combined_products =& $account['combined'];
if(!empty($combined_products)) {
foreach($combined_products as $prod_id => $combined) {
usort($combined_products[$prod_id], array($this, "_compareBoxes"));
}
// Flip weights once we finish with this account
$last_box = end($combined_products);
$last_box = array_pop($last_box);
reset($combined_products);
if($this->weight == 1) {
$this->weight = -1;
if($last_box['size'] == 3) {
asort($combined_products);
}
} else {
if($last_box['size'] == 4) {
arsort($combined_products);
}
$this->weight = 1;
}
foreach($combined_products as $combined) {
$account['output'][] = $combined;
}
foreach($account['separated'] as $separate) {
$account['output'][] = $separate;
}
}
} else {
if(isset($account['separated']))
$account['output'] = $account['separated'];
}
}
$deliveries = count($rows['deliveries']);
for($i = 0; $i < $deliveries; $i++) {
$account =& $rows['deliveries'][$i];
$account['output'] = array();
if(isset($account['combined'])) {
$combined_products =& $account['combined'];
if(!empty($combined_products)) {
foreach($combined_products as $prod_id => $combined) {
usort($combined_products[$prod_id], array($this, "_compareBoxes"));
}
// Flip weights once we finish with this account
$last_box = end($combined_products);
$last_box = array_pop($last_box);
reset($combined_products);
if($this->weight == 1) {
$this->weight = -1;
if($last_box['size'] == 3) {
asort($combined_products);
}
} else {
if($last_box['size'] == 4) {
arsort($combined_products);
}
$this->weight = 1;
}
foreach($combined_products as $combined) {
$account['output'][] = $combined;
}
foreach($account['separated'] as $separate) {
$account['output'][] = $separate;
}
}
} else {
if(isset($account['separated']))
$account['output'] = $account['separated'];
}
}
$rows['output'] = $rows['pickups'];
array_push($rows['output'], $rows['deliveries']);
$output = '';
foreach($rows['output'] as $account_id => $boxes) {
if(!empty($boxes['output'])) {
foreach($boxes['output'] as $labels) {
if(!empty($labels)) {
foreach($labels as $label) {
$output .= implode(',', $label) . "<br>";
}
}
}
}
}
The _compareBoxes method looks like this:
private function _compareBoxes($a, $b) {
if($a['size'] == $b['size']) {
return 0;
}
if($this->weight == 1) {
// Medium first, then Large
return ($a['size'] < $b['size']) ? -1 : 1;
}
if($this->weight == -1) {
// Large first, then Medium
return ($a['size'] > $b['size']) ? -1 : 1;
}
}

Categories