PHP array getting duplicate values - php

I am working on displaying information from my database. When I did print_r in the model/itemTile.php below to check on my array, $this->display, I noticed it had stored 2 copies of the data from my database. I checked my database, and there was definitely only one copy of the data.
I created a counter variable, $this->counter, to see what the surrounding while loop was doing. The original data had 6 non-duplicating rows. As you may see in the jpg attached below, the program increments and echo the counter to 6, then it does the "print_r($this->display)" line that is outside of the while loop, then for some strange reason goes back to the while loop, increment the counter, and print the $this->counter and $this->display again!
I can remove the duplicate, but I would much prefer to figure out why exactly there are two copies of the value to begin with.
Since this was originally a PHP class project that focus on MVC, everything is placed into controller, model, and view. I have included the relevant model and view code below:
Jpg:
PHP Site
model/itemTile.php
<?php
require_once('siteInfo.php');
class itemTile implements siteInfo {
private $term;
private $session;
private $result;
private $display = array();
private $counter = 0;
public function __construct($session) {
$this->session = $session;
}
public function getContent() {
$this->result = $this->session->db->prepare("SELECT productName, sciName, price FROM products");
$this->result->execute();
$this->result->bind_result($pN, $sN, $pz);
while ($this->result->fetch()) {
if (array_key_exists($pN, $this->display)) {
$this->display[$pN]["price"][] = $pz;
} else {
$this->display += [
$pN => [ //Product Name was used to id array because not all item have sciName,
"sciName" => [$sN], //and not all item have only 1 sku (1 item with different size = multiple pid).
"price" => [$pz]
]
];
}
$this->counter++;
echo $this->counter . "<br />";
}
$this->result->close();
print_r($this->display);
echo "<br />";
}
public function setContent() {
$this->getContent();
return $this->display;
}
}
?>
view/itemTile.php
<?php
class itemTileView {
private $model;
public function __construct(itemTile $model) {
$this->model = $model;
}
public function output(){
foreach ($this->model->setContent() as $item => $detail) {
$itemLink = preg_replace('/\s+/','_', $item);
echo "<div class= 'tileSpace'>";
echo "<a href='itemPages/" . $itemLink. "/home.php'>";
echo "<img alt='" . $item . "' src='itemPages/" . $itemLink . "/thumbnail.jpg' width='100' height='100'>";
echo "</a>";
echo "<p>" . $item . ": " . $detail["sciName"][0] . "</p>";
if (count($detail["price"]) > 1) {
echo "<p>" . min($detail["price"]). " - " . max($detail["price"]). "</p>";
} else {
echo "<p>" . $detail["price"][0] . "</p>";
}
echo "</div>";
}
}
}
?>
Can anyone spot where is the problem occurring?

use php function array_unique();
array_unique($arrayname);
using this you will get unique values from array.it avoids duplicate values

Related

Difference between array type and object type in PHP [duplicate]

This question already has answers here:
PHP Objects vs Arrays -- Performance comparison while iterating
(11 answers)
Closed 7 years ago.
As I know, an array in php can designed by key and value.
e.q.
$person = array(
'name'=>'JOSH',
'age'=>18
);
It likes an object but just defined by another way.
e.q.
class info{
$name;
$age;
}
$person = new info();
$person->name = 'JOSH';
$person->age = 18;
I always use array in PHP, but some of my co-workers they say the object type is better than array type.
But I don't understand what different between array type and object type.
Can someone tell me what different between this two types if I just want to declare variable in PHP ?
There are a lot of differences, but the object is more powerfull.
Is in a way to avoid rewrite code, and clean the code.
Think you want to do some operations to numbers in an array:
To keep it simple, I suppose you already get the values from array or object.
<?
$item = array(
'name'=>'carrot',
'price'=>0.20,
'stock' => 15
);
?>
For example, in an shop context, you want to get the price befor buy, and update the stock.
<?
function getprice($item){
return $item['price'];
}
function substock($item,$units){
$item['stock'] = $item['stock'] - $units;
}
echo getprice($item);
echo "<br/>";
echo substock($item,"3");
?>
It will output something like:
0.20
12
That can be a way, but what can we do with the objects:
<?
class items{
var $name , $price, $stock;
function __construct($in_name, $in_price, $in_stock){
if (!empty($in_name)){$this->name = $in_name;}
if (!empty($in_price)){$this->price = $in_price;}
if (!empty($in_stock)){$this->stock = $in_stock;}
}
function getprice(){
return $this->price;
}
function substock($units){
$newstock = $this->stock - $units;
$this->stock = $newstock;
return $newstock;
}
}
$item = new items("carrot","0.20","15");
echo $item->getprice();
echo "<br/>";
echo $item->substock("3");
?>
It will output something like:
0.20
12
Till this point is not a prety much difference, is'n it?
But imagine you want to create a bigger thing. Just play around with it.
Now I want to load an item just with the name of the carrot.
Then changing the method construct to be able to create an objet with different inputs:
var $name , $price, $stock;
function __construct($in_name, $in_price=NULL, $in_stock=NULL){
$args = func_num_args();
if ($args == 1){
$this->name = $in_name;
$this->fromdb($in_name);
}else{
if (!empty($in_name)){$this->name = $in_name;}
if (!empty($in_price)){$this->price = $in_price;}
if (!empty($in_stock)){$this->stock = $in_stock;}
}
}
function fromdb($name){
$sql = "SELECT * FROM items WHERE name = '" . $name . "'";
//... here we bring from database the item and put in an array called $itemdb.I skip this part to do it shorter. If you want, ask about and I'll post this peace and the database objet.
$this -> price = $itemdb['price'];
$this -> stock = $itemdb['stock'];
}
function getprice(){
return $this->price;
}
function substock($units){
$newstock = $this->stock - $units;
$this->stock = $newstock;
return $newstock;
}
}
$item = new items("carrot");
echo $item->getprice();
echo "<br/>";
echo $item->substock("3");
?>
If the value in the database is same as the example before.It will output something like:
0.20
12
But from here you have infinite posibilities. Just play more.
Give a family item, and creating new methods.
<?
class items{
var $name , $price, $stock, $family;
function __construct($in_name, $in_price=NULL, $in_stock=NULL, $in_family=NULL){
$args = func_num_args();
if ($args == 1){
$this->name = $in_name;
$this->fromdb($in_name);
}else{
if (!empty($in_name)){$this->name = $in_name;}
if (!empty($in_price)){$this->price = $in_price;}
if (!empty($in_stock)){$this->stock = $in_stock;}
if (!empty($in_family)){$this->family = $in_family;}
}
}
function fromdb($name){
$sql = "SELECT * FROM items WHERE name = '" . $name . "'";
//... here we bring from database the item and put in an array called $itemdb. I skip this part to do it shorter. If you want, ask about and I'll post this peace and the database objet.
$this -> price = $itemdb['price'];
$this -> stock = $itemdb['stock'];
$this -> family = $itemdb['family'];
}
function getprice(){
return $this->price;
}
function getfamily(){
return $this->family;
}
function substock($units){
$newstock = $this->stock - $units;
$this->stock = $newstock;
return $newstock;
}
function veggiesinfamily(){
$sql = "SELECT count(name),family FROM items WHERE family = '" . $this->family . "'";
//... here we bring from database the number of item of a family product in $number. I skip this part to do it shorter. If you want, ask about and I'll post this peace and the database objet.
return $number;
}
function familystock(){
$sql = "SELECT SUM(stock),family FROM items WHERE family = '" . $this->family . "'";
//... here we bring from database the sum of stock items of a family product in $number. I skip this part to do it shorter. If you want, ask about and I'll post this peace and the database objet.
return $number;
}
}
$item = new items("carrot");
echo "There are " . $item->veggiesinfamily() . $item->getfamily() . " kinds.<br/>";
echo "There are " . $item->familystock() . " units of " . $item->getfamily();
?>
We have also in our database an item: potato, 0.3, 10, roots (name, price, stock, family)
If the value in the database have as family roots and as elements carrot and potatoe. The output will be.
There is 2 roots kinds.
There is 25 units of roots.
And so on.
If you load the objet from an external file as item_class.php, and load as include("item_class.php"), can grow your script easily.
Cheers.

printing an variable of an object that's inside an array that's inside an object

Well, ive been trying to get my crm to print multiple contacts for each company but i cant get it to work
Company is a class,companycontactis a class
//class called company
function __construct($idklanten,$naam,$adres,$postcode,$stad,$contacten){
$this->idklanten=$idklanten;
$this->naam=$naam;
$this->adres=$adres;
$this->postcode=$postcode;
$this->stad=$stad;
$this->contacten=$contacten;
}
//class called contact
function __construct($idcontactklanten,$voornaam,$tussenvoegsel,$achternaam,$tel,$email,$klantID){
$this->idcontactklanten=$idcontactklanten;
$this->voornaam=$voornaam;
$this->tussenvoegsel=$tussenvoegsel;
$this->achternaam=$achternaam;
$this->tel=$tel;
$this->email=$email;
$this->klantID=$klantID;
}
//getname for a contact
function getNaam() {
if(strlen($this->gettussenvoegsel()) == 0) {
return $this->getvoornaam()." ".$this->getachternaam()."";
}
else {
return $this->getvoornaam() . " " . $this->gettussenvoegsel() . " " . $this->getachternaam();
}
}
//function for getting the names from my object company,array with objects of contacts
function getcontacten(){
$ct=$this->contacten[$teller];
$txt="";
for($teller=0;$teller<10;$teller++){
$txt+=$ct->getNaam()."<br>";
}
return $txt;
}
then on my index page when i call getcontacten() it does not work comparing to my other get function which do work. it just outputs a 0
Any help is appreciated
Your biggest error would be the following:
$txt+=$ct->getNaam()."<br>";
Should be
$txt.=$ct->getNaam()."<br>";
Because to append to a string you use ".=", not "+=".
Also I don't know if the other part of you code works, I would write something like the following:
$txt = "";
foreach ($this->contacten as $ct){
$txt .= $ct->getNaam() . "<br />";
}
return $txt;
or
$txt = "";
for ($i = 0; $i < count($this->contacten); $i++){
$txt .= $this->contacten[$i]->getNaam() . "<br />";
}
return $txt;

Understanding PHP Class OOP structure [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I'm trying to create a class function but somehow it won’t work and I can’t figure out what’s the problem. Is it the way I declare the variable or what so ever?
<?php
class Car{
var $model;
var $make;
var $speed;
function Car ( $model, $make, $speed)
{
$this->model = $model;
$this->make = $make;
$this->speed = $speed;
}
function accelerate ($speed)
{
$add = 5;
$speed = $speed + $add;
return $speed;
}
function get_status()
{
echo "Car status : \n";
echo "Model :" $this-> model "\n";
echo "Make :" $this-> make "\n\n";
}
function get_speed()
{
return $this->speed;
}
}
?>
<?php
$car1 = new Car();
$car1 -> get_status("Vios", "Toyota");
for( $i = 0; $i < 5 ; $i++)
{
echo "Accelerating... <br> \n";
echo "Current speed : accelerate(5) km/h <br>";
}
?>
Lots of issues with your code. But at least this cleaned up version should work without the script dying completely. Here is a breakdown of what I did:
Set the variables that were set as var to public since that is the preferred method of setting variables.
In function Car, I set default values for $model, $make & $speed so if they are not passed—like in your example—there is at least a default value to act on.
Your echo lines in get_status did not have the . for concatenation so they were not properly concatenating the strings.
Then you setting $this-> make and $this-> model with empty spaces is syntactically incorrect. So set those to $this->make and $this->model.
Then when you are calling the class, you set this "Current speed : accelerate(5) km/h <br>"; which is syntactically incorrect as well. So set that to echo "Current speed : " . $car1->accelerate(5) . " km/h <br>"; so it can actually echo values.
But that said, unclear on what the output is for this code. The logic is a bit of a mess. But at least it’s not completely dying like it did before!
And here is the cleaned up code:
class Car {
public $model;
public $make;
public $speed;
function Car ($model = 0, $make = 0, $speed = 0) {
$this->model = $model;
$this->make = $make;
$this->speed = $speed;
}
function accelerate ($speed) {
$add = 5;
$speed = $speed + $add;
return $speed;
}
function get_status () {
echo "Car status : \n";
echo "Model :" . $this->model . "\n";
echo "Make :" . $this->make . "\n\n";
}
function get_speed () {
return $this->speed;
}
}
$car1 = new Car();
$car1->get_status("Vios", "Toyota");
for( $i = 0; $i < 5 ; $i++) {
echo "Accelerating... <br> \n";
echo "Current speed : " . $car1->accelerate(5) . " km/h <br>";
}
And—like I said before—since the way you are calling the class makes little sense to the structure you have, I slightly reworked the code above so it loops through an array of car values like this:
$car_array = array("Vios", "Toyota");
foreach ($car_array as $car_value) {
$car1 = new Car($car_value);
$car1->get_status();
for( $i = 0; $i < 5 ; $i++) {
echo "Accelerating... <br> \n";
echo "Current speed : " . $car1->accelerate(5) . " km/h <br>";
}
}
Add a constructor like this:
public function __construct($model = 0, $make = 0, $speed = 0) {
$this->model = $model;
$this->make = $make;
$this->speed = $speed;
}
http://us3.php.net/manual/en/language.oop5.decon.php
When concatenating strings, you must use the dot operator:
echo "abcd" . "efgh";

How to use array in function to get only value I want

I am trying to work this function in wordpress theme the way where I can get value only what I want and not all to gather. I am not much familiar with using array in function so I need you expert help to make it works and I would really appreciate that.
Here is my code
function gallery_artist($arg=null, $arg2=null, $arg3=null){
global $png_gallery_meta;
$png_gallery_meta->the_meta();
$gallery = get_post_meta(get_the_ID(), $png_gallery_meta->get_the_id(), TRUE);
$gallery_value = $gallery['image_artist'];
$artist_info = $gallery_value;
$string = $artist_info;
$artist = substr($string, 0, stripos($string, "/") );
// getting first name and last name from user id
$author_first_name = get_userdata(basename($string))->first_name;
$author_last_name = get_userdata(basename($string))->last_name;
$author_full_name = $author_first_name . ' ' . $author_last_name;
$user_id = '<a href=" ' . get_author_posts_url(basename($string)) . ' " title="more submissions of ' . $author_first_name .' '. $author_last_name . ' " >' . $artist . '</a>';
$arg = $author_first_name;
echo $arg;
$arg2 = $author_last_name;
echo $arg2;
$arg3 = $user_id;
echo $arg3;
}
After than I want to use this function to get any value I want and not unnecessary to render all three to gather. Means if I want only first name than I pass value only for that and it will render only first name so on..
Here how I want to use something. but you can suggest any code and type of function I have no issue.
<?php call_user_func_array('gallery_artist', array('first_name','last_name','artist_id') ) ?>
Big Big thanks to you all..
Try replacing the bottom section with this:
if(!is_null($arg))
{
$arg = $author_first_name;
echo $arg;
}
if(!is_null($arg2))
{
$arg2 = $author_last_name;
echo $arg2;
}
if(!is_null($arg3))
{
$arg3 = $user_id;
echo $arg3;
}

php script executes but no output

I have gone through all the similar questions and nothing fits the bill.
I am running a big script, which ran on chron on an old server but failed on the new so I am working on and testing in browser.
I have two functions, one pulls properties from the database, and then runs them through another which converts the price into 4 currencies, and if the value is different updates the row. The functions are as follows:
<?php
function convert_price($fore_currency, $aft_currency, $amount)
{
echo "going into convert<br/>";
$url = "http://www.currency.me.uk/remote/ER-ERC-AJAX.php?ConvertFrom=" . $fore_currency .
"&ConvertTo=" . $aft_currency . "&amount=" . $amount;
if (!is_int((int)file_get_contents($url))) {
//echo "Failed on convert<br/>";
return false;
} else {
//echo "Conversion done";
return (int)file_get_contents($url);
}
}
function run_conversion($refno = '', $output = false)
{
global $wpdb;
$currencies = array("GBP", "EUR", "TRY", "USD");
$q = "SELECT * FROM Properties ";
$q .= (!empty($refno)) ? " WHERE Refno='" . $refno . "'" : "";
$rows = $wpdb->get_results($wpdb->prepare($q), ARRAY_A);
$currencies = array("USD", "GBP", "TRY", "EUR");
//$wpdb->show_errors();
echo "in Run Conversion " . "<br/>";
foreach ($rows as $row) {
echo "In ROw <br/>";
foreach ($currencies as $currency) {
if ($currency != $row['Currency'] && $row['Price'] != 0) {
$currfield = $currency . "_Price";
$newprice = convert_price($row['Currency'], $currency, $row['Price']);
echo "Old Price Was " . $row['Price'] . " New Price Is " . $newprice . "<br/>";
if ($newprice) {
if ($row[$currfield] != $newprice) {
$newq = "UPDATE Properties SET DateUpdated = '" . date("Y-m-d h:i:s") . "', " .
$currfield . "=" . $newprice . " WHERE Refno='" . $row['Refno'] . "'";
$newr = $wpdb->query($newq);
if ($output) {
echo $newq . " executed <br/>";
} else {
echo "query failed " . $wpdb->print_error();
}
} else {
if ($output) {
echo "No need to update " . $row['Refno'] . " with " . $newprice . "<br/>";
}
}
} else {
echo "Currency conversion failed";
}
}
}
}
}
?>
I then run the process from a seperate file for the sake of chron like so:
require($_SERVER['DOCUMENT_ROOT'] . "/functions.php"); // page containing functions
run_conversion('',true);
If I limit the mysql query to 100 properties it runs fine and I get all the output in a nice stream. But when I try to run it in full the script completes (I can see from rows updated in db) but no output. I have tried upping the memory allowance but no joy. Any ideas gratefully received. Also, I get a 500 error when changing from Apache Module to CGI. Any ideas on that also well received as ideally I would like to turn site onto fastCGI.
You're running out of memory most likely. Probably in your DB layer. Your best bet is to unset your iterative values at the end of each loop:
foreach ( $rows as $row ) {
...
foreach ( $currencies as $currency ) {
...
unset( $currency, $newr, $currfield, $newprice );
}
unset( $row );
}
This will definitely help.
As another answer suggests you may be running out of memory, but if you make an HTTP call everytime the loop is running, and you have 100+ currencies, this may also cause the problem. Try limit it to 5 currencies for example.
If this is indeed the problem I would split the process, so a chunk of currencies have their respective value updated per cron job, instead of everything.

Categories