How to dynamically add to object array? - php

So like when working with mysql_fetch_object(), how do you do things like this:
$array = array();
while($row = mysql_fetch_object($result))
{
$array[] = $row;
}
How do you accomplish that with objects instead of an array? Like,
$object = new stdClass;
while($row = mysql_fetch_object($result))
{
$object[] = $row;
}
Is there a way to do this without a lot of ugly typecasting?

The first method is correct,
it should assign all the objects into $array,
like an array,
you can access via
$arr[0]->$COLUMN ...
I bet you are not referring to this :-
$object = new stdClass;
while($row = mysql_fetch_object($result))
{
$props = "object_{$cnt}";
$object->$props = $row;
++$cnt;
}
The second method is assign each object into property of $object,
and you can assign the property as :-
$object->object_0->$COLUMN ...

Other languages (like C++, C# and Java) support "generics" so you don't have to do "a lot of ugly typecasting". PHP does't - hence the general need for a cast.
But in your case ... if "$row" starts out as an object when you put it into the array ... don't you get the same object back when you de-reference the array?

$object = array();
while($row = mysql_fetch_object($result))
{
$object[] = $row;
}
$object = new stdClass($object);
or
class myClass{
private $counter = 0;
public function add($row){
$count = $counter++;
$this->$count = $row;
}
}
$object = new myClass();
while($row = mysql_fetch_object($result))
{
$object->add($row);
}
or
class myClass implements ArrayAccess{
private $counter = 0;
public function offsetSet($offset, $value) {
if (is_null($offset)) {
$count = $counter++;
$this->$count = $value;
} else {
$this->$offset = $value;
}
}
public function offsetExists($offset) {
return isset($this->$offset);
}
public function offsetUnset($offset) {
unset($this->$offset);
}
public function offsetGet($offset) {
return isset($this->$offset) ? $this->$offset : null;
}
}
$object = new myClass();
while($row = mysql_fetch_object($result))
{
$object[] = $row;
}

Related

Error when printing how many levels are visible in tree in PHP

I am receiving the error "Using $this when not in object context". I think I might be using the class node incorrectly. I cannot figure out where I am going wrong at this point.
I am trying to get the answer 4 in the case of a tree like the below. This is because there are 4 visible layers.
$root = new TreeNode(8);
$root->left = new TreeNode(3);
$root->right = new TreeNode(10);
$root->left->left = new TreeNode(1);
$root->left->right = new TreeNode(6);
$root->left->right->left = new TreeNode(4);
$root->left->right->right = new TreeNode(7);
$root->right->right = new TreeNode(14);
$root->right->right->left = new TreeNode(13);
class TreeNode{
public $val;
public $left;
public $right;
public function __construct($val=0) {
$this->val = $val;
$this->left = NULL;
$this->right = NULL;
}
}
function findLeft($root){
$queue = $root;
while(!empty($queue)){
$size = sizeof($queue);
$i = 0;
$answer = 0;
while($i<$size){
$i= $i+1;
//if first node print
if ($i == 1){
$answer += 1;
}
if($this->left){
array_push($queue, $this->left);
}
if($this->right){
array_push($queue, $this->right);
}
array_unshift($queue); //shift first item
}
} return $queue;
}
//calling function
function visibleNodes($root) {
// Write your code here
if(empty($root)){
return 0;
} else {
$answer = findLeft($root);
}
return $answer;
}

PHP OOP not passing variables in the class

I have a PHP class that is meant to get a mysqli query, make a multidimensional array, and currently just echo the whole array. It is this code:
include("connect.php");
class database
{
public $motto;
public $motto_array = array();
public $rating;
public $rating_array = array();
public $category;
public $score;
private $mysqli;
public $counter_array = array();
public $multi_dim_values = array();
public $multi_dim_category = array();
function setMysqli($mysqli)
{
$this->mysqli = $mysqli;
}
function setCategory($category)
{
$this->category = $category;
}
function query_category()
{
if ($stmt = $this->mysqli->prepare("SELECT motto, score FROM mottos WHERE category=? ORDER BY score DESC"))
{
$stmt->bind_param("s", $this->category);
$stmt->execute();
$stmt->bind_result($motto, $ranking);
while ( $stmt->fetch() ) {
$this->motto_array[] = $motto;
$this->rating_array[] = $ranking;
}
$stmt->close();
}
}
function multi_dim_array()
{
$multi_dim_values = array($this->motto_array, $this->rating_array);
$counter_array = range(0,count($this->motto_array)-1);
foreach($counter_array as $index => $key) {
$foreach_array = array();
foreach($multi_dim_values as $value) {
$foreach_array[] = $value[$index];
}
$multi_dim_category[$key] = $foreach_array;
}
return $multi_dim_category;
}
}
$class = new database;
$class->SetMysqli($mysqli);
$class->SetCategory("person");
$class->query_category();
print_r($class->multi_dim_array);
print_r($class->multi_dim_category);
connect.php has the database connection information for the mysqli.
I am learning OOP, so I did this in procedural, and it works fine, with this code:
include("connect.php");
function category($mysqli, $cat)
{
if ($stmt = $mysqli->prepare("SELECT motto, score FROM mottos WHERE category=? ORDER BY score DESC"))
{
$stmt->bind_param("s", $cat);
$stmt->execute();
while($stmt->fetch())
{
printf ("[%s (%s) in %s] \n", $motto, $ranking, $category);
$array .= compact("motto", "category", "ranking");
}
print_r($array);*/
$a = array();
$b = array();
$c = array();
$stmt->bind_result($motto, $ranking);
while ( $stmt->fetch() ) {
$a[] = $motto;
$b[] = $ranking;
}
$result = array();
$values = array($a, $b);
$c = range(0,count($a)-1);
foreach($c as $index => $key) {
$t = array();
foreach($values as $value) {
$t[] = $value[$index];
}
$result[$key] = $t;
}
return $result;
$stmt->close();
}
}
$cat = "person";
$array_one = category($mysqli, $cat);
print_r($array_one);
This prints the multidimensional array just like I want it to.
What am I doing wrong in the OOP code?
Thank you.
Your code:
print_r($class->multi_dim_array);
You forgot the (), so you're not invoking the method. You're accessing a (non-existent) property. Try this:
print_r($class->multi_dim_array());

PHP how can I find out right properties within Object

class a {
public $a = "3";
public $b = "0";
public $b = "3";
public $c = "0";
public $d = "0";
public $e = "0";
public $g = "0";
}
How can I find out which properties are greater than zero?
You can use the get_class_vars function outside the object itself like that:
$a = new a();
$class_vars = get_class_vars(get_class($a));
foreach ($class_vars as $name => $value) {
if ($value > 0) {
echo "$name : $value\n";
}
}
put this method inside your class and it will return all vars in array:
public function test() {
$vars = get_object_vars($this);
$r = array();
foreach($vars as $k => $v) {
if($v > 0){ $r[$k] = $v; }
}
return $r;
}

php function and change two loops to one loop?

I have a simple function:
function test(){
//some code
$X_has_val = $Y_has_val= array();
foreach ($A as $id => $row){
if(is_take($id)){
$X_has_val[$id] = $row;
}
}
foreach ($B as $id => $row){
if(is_take($id)){
$Y_has_val[$id] = $row;
}
}
//some code
}
I did this for get the equivalence
function test(){
//some code
$X_has_val = $Y_has_val= array();
foreach(array($A, $B) as $key=>$value){
foreach ($value as $id => $row){
if(is_take($id)){
$X_has_val[$id] = $row;
continue;
$Y_has_val[$id] = $row;
}
}
}
//some code
}
Looks like all you need is array_filter()
$X_has_cc = array_filter($A, 'isTake');
$Y_has_cc = array_filter($B, 'isTake');
like e.g. in
<?php
test();
function test() {
$A = array(1,2,3,4,5,6,7,8,9,10);
$B = array(99,100,101,102,103,104);
$X_has_cc = array_filter($A, 'isTake');
$Y_has_cc = array_filter($B, 'isTake');
var_dump($X_has_cc, $Y_has_cc);
}
// select "even elements"
function isTake($x) {
return 0==$x%2;
}
(and sorry, no, your approach doesn't make much sense ;-))

php - quick refactoring

I have 2 methods, that are pretty much exactly the same and I'd likie someone to help me refactor them:
public static function searchFromVideoRequest($word, $returnPropelObjects = false)
{
$c = new Criteria();
$c->addJoin(YoutubeVideoPeer::ID,ItemPeer::YOUTUBE_VIDEO_ID);
$c->addSelectColumn(self::TITLE);
$c->addSelectColumn(self::ID);
$c->add(ItemPeer::TITLE, '%'.$word.'%', Criteria::LIKE);
$c->addAnd(self::YOUTUBE_VIDEO_ID, null, Criteria::ISNOTNULL);
$c->addAscendingOrderByColumn(self::TITLE);
if ($returnPropelObjects)
return self::doSelect($c);
$stmt = self::doSelectStmt($c);
$results = array();
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
$results[] = $row;
}
return $results;
}
public static function searchFromFlickrRequest($word, $returnPropelObjects = false)
{
$c = new Criteria();
$c->addJoin(FlickrPhotoPeer::ID,ItemPeer::FLICKR_PHOTO_ID);
$c->addSelectColumn(self::TITLE);
$c->addSelectColumn(self::ID);
$c->add(ItemPeer::TITLE, '%'.$word.'%', Criteria::LIKE);
$c->addAnd(self::FLICKR_PHOTO_ID, null, Criteria::ISNOTNULL);
$c->addAscendingOrderByColumn(self::TITLE);
if ($returnPropelObjects)
return self::doSelect($c);
$stmt = self::doSelectStmt($c);
$results = array();
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
$results[] = $row;
}
return $results;
}
Thanks
To refactor such methods you can split up them into a few methods that will contain common code and make them private, so no one can use them outside the class:
public static function searchFromVideoRequest($word, $returnPropelObjects = false)
{
$c = self::buildSearchCriteria($word);
$c->addJoin(YoutubeVideoPeer::ID,ItemPeer::YOUTUBE_VIDEO_ID);
$c->addAnd(self::YOUTUBE_VIDEO_ID, null, Criteria::ISNOTNULL);
return self::getSearchResult($c, $returnPropelObjects);
}
public static function searchFromFlickrRequest($word, $returnPropelObjects = false)
{
$c = self::buildSearchCriteria($word);
$c->addJoin(FlickrPhotoPeer::ID,ItemPeer::FLICKR_PHOTO_ID);
$c->addAnd(self::FLICKR_PHOTO_ID, null, Criteria::ISNOTNULL);
return self::getSearchResult($c, $returnPropelObjects);
}
private static function buildSearchCriteria($word)
{
$c = new Criteria();
$c->addSelectColumn(self::TITLE);
$c->addSelectColumn(self::ID);
$c->add(ItemPeer::TITLE, '%'.$word.'%', Criteria::LIKE);
$c->addAscendingOrderByColumn(self::TITLE);
return $c;
}
private static function getSearchResult($c, $returnPropelObjects)
{
if ($returnPropelObjects)
return self::doSelect($c);
$stmt = self::doSelectStmt($c);
$results = array();
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
$results[] = $row;
}
return $results;
}
PS: And I think the question is OK.

Categories