php output constructor array - php

I tried executing the code below to output each value from an array, end up result show:
Notice: Array to string conversion in C:\xampp\htdocs\test\tutor.php on line 22
_data : Array
PHP
<?php
class CateData
{
private $_data = array();
public function __construct($data){
$this->_data = $data;
}
}
$data = array(
'a'=>'Cate1',
'b'=>'Cate2',
'c'=>'Cate3',
'd'=>'Cate4'
);
$cate = new CateData($data);
foreach($cate as $key => $val){
echo $key." : ". $val;
}
?>
How can I solve this?

You're looping on the class object and not on the actual data.
In your class add:
public function getData(){
return $this->_data;
}
Then change:
foreach($cate as $key => $val){
echo $key." : ". $val;
}
To:
foreach($cate->getData() as $key => $val){
echo $key." : ". $val;
}

While the accepted answer is better, an alternative is to change the scope so you you dont need to add a getData() method. But can then access the class variables directly.
//change the variable to public, and loop $cate->_data
class CateData
{
public $_data = array();
public function __construct($data){
$this->_data = $data;
}
}
$data = array(
'a'=>'Cate1',
'b'=>'Cate2',
'c'=>'Cate3',
'd'=>'Cate4'
);
$cate = new CateData($data);
foreach($cate->_data as $key => $val){
echo $key." : ". $val;
}

First you should clear the differences between public protect and private.
In your code, you should change your _data to public because you want to visit outside your class.
Then change:
foreach($cate as $key => $val){
echo $key." : ". $val;
}
to:
foreach($cate->_data as $key => $val){
echo $key." : ". $val;
}

Related

How looks good structure of construct for creating multidimensial array

I am trying to create constructor which creates an multidimensional array. My result should be like this:-
Checkout my array $result_array
For now I have error: Illegal offset type. Note that I have als use __toString() becose I work on xml data.
class Property {
public $xmlClass;
public $elemClass = '';
public $first_array = array();
public $result_array = array();
public $data = '';
public $data2 = '';
public function __construct($xml, $elem) {
$this->xmlClass = $xml;
$this->elemClass = $elem;
foreach ($xml->xpath('//*[#baza]') as $val) {
$this->first_array[] = $val;
foreach ($val->ksiazka as $value) {
$data = $value->$elem->__toString();
$this->result_array[$this->first_array][] = $data;
}
}
}
public function getResult() {
return $this->result_array;
}
}
$result_autor = new Property($xml, 'autor');
$autor = $result_autor->getResult();
You need to change your two foreach() like below:-
foreach($xml->xpath('//*[#baza]') as $val) {
//$this->first_array[] = $val; not needed
foreach($val->ksiazka as $key=> $value){ //check $key here
$data = $value->$elem->__toString();
$this->result_array[$key][] = $data; // add $key hear
}
}
If the above not worked then check this too:-
foreach($xml->xpath('//*[#baza]') as $key=> $val) { //check $key here
//$this->first_array[] = $val; not needed
foreach($val->ksiazka as $value){
$data = $value->$elem->__toString();
$this->result_array[$key][] = $data; // add $key hear
}
}

Convert only matching keys from an array into object properties that match

I am trying to convert only matching keys from an associative array into object properties that match them. The code I have below gives an error of Unidentified variable : key on this line if(array_key_exists($array[$key], $classprop)){.
<?php
class assoctoprop {
public $fname;
public $lname;
public $email;
public function assign(){
$array = array("fname"=>"firstname", "lname"=>"lastname", "email"=>"my#email.com" );
$classprop = get_object_vars($this);
if(array_key_exists($array[$key], $classprop)){
foreach($classprop as $key=>$value){
$this->{$key} = $array[$key];
}
}
}
}
$user = new assoctoprop;
$user->assign();
echo $user->fname."<br/>";
echo $user->lname."<br/>";
echo $user->email."<br/>";
?>
If I modify the method as such
public function assign(){
$array = array("fname"=>"firstname", "lname"=>"lastname", "email"=>"my#email.com" );
foreach(get_object_vars($this) as $key=>$value){
$this->{$key} = $array[$key];
}
}
it works, but when one key do not match property or vice versa, an undefined index is shown.
You need to move the if statement inside the foreach loop because outside of it, $key is undefined. You also need to check for this $key in your array:
foreach($classprop as $key=>$value){
if(array_key_exists($key, $array)){
You could of course also do it the other way around, loop over $array and check if the property exists in the object.
public function assign(){
$array = array("fname"=>"firstname", "lname"=>"lastname", "email"=>"my#email.com" );
foreach(get_object_vars($this) as $key=>$value){
if(isset($array[$key])){
$this->{$key} = $array[$key];
}
}
}
please add if(isset($array[$key]) check
or better of you still need to init unmutched vars in an object
public function assign(){
$array = array("fname"=>"firstname", "lname"=>"lastname", "email"=>"my#email.com" );
foreach(get_object_vars($this) as $key=>$value){
$this->{$key} = isset($array[$key])? $array[$key] : "";
}
}

php read mongodb.findone() returned json values and create object

I have an employee class and i want to initialize the employee object from mongodb.findone() returned array.
foreach($res as $key => $value){
echo $value; // here values printed
}
but i need to do something like( if key = 'first_name' then employee_obj->set_first_name($value), if key = 'last_name' then employee_obj->set_last_name($value)... ) can you help me?
$employee = new Employee;
foreach($res as $key => $value){
if (property_exists($employee, $key)) {
$employee->$key = $value;
}
}
$employee->$key = $value is dynamically assigning $key property to the employee. Example:
$key = "name";
$employee->$key = "John Doe";
echo $employee->name; // John Doe
If you want to do this with private or protected properties you need to do the assignment within the class or instance:
class Employee {
// ...
private $name;
// lets you assign properties by passing in an array
public function __construct($arr = array()){
if count($arr) {
foreach($arr as $key => $value){
if (property_exists($this, $key)) {
$this->$key = $value;
}
}
}
}
}
$joe = new Employee(array('name' => 'Joe'));
echo $joe->name // Joe
$e = new Employee;
foreach($res as $k => $v){
if($k == 'first_name'){
$e->set_first_name($v);
}elseif($k == 'last_name'){
$e->set_last_name($v);
}else{
$e->$k = $v;
}
}
Does exactly that.

print dynamicly set proprites in object

how to print dynamical add properties in bellow class?
class Car {
function __construct() {
}
function setInfo($car_arr) {
foreach ($car_arr as $key => $value) {
$this->{$key} = $value;
}
}
}
set class object like bellow
$car1 = new Car();
$car1->setInfo(array('make' => 'Toyota', 'model' => 'scp10'));
$car2 = new Car();
$car2->setInfo(array('anme1' => 'value1', 'anme2' => 'value2'));
now I want to to print car object bellow
make = Toyota
model = scp10
Try :
$car1 = new Car();
$car1->setInfo(array('make' => 'Toyota', 'model' => 'scp10'));
echo $car1->make;
echo $car1->model;
<?php
class Car {
function __construct() {
}
function setInfo($car_arr) {
foreach ($car_arr as $key => $value) {
$this->{$key} = $value;
}
}
}
$car1 = new Car();
$car1->setInfo(array('make' => 'Toyota', 'model' => 'scp10'));
echo "Make value is : " . $car1->make. ", Model value is : ". $car1->model;
?>
above code output Make value is : Toyota, Model value is : scp10
Please consider storing the properties explicitly like I pointed out in this answer:
<?php
class Car {
private $data = array();
function setInfo(array $carInfo) {
foreach ($carInfo as $k => $v) {
$this->data[$k] = $v;
}
return $this;
}
function __set($key, $val) {
$this->data[$key] = $val;
}
function __get($key) {
return $this->data[$key];
}
}
$car = new Car();
$car->setInfo(array('make' => 'Toyota', 'warranty' => '5 years'));
I'd consider it more "clean", but that's probably debatable.
I think you look for something like this PHP Magic Methods
For example this one:
<?php
class A
{
public $var1;
public $var2;
public static function __set_state($an_array) // As of PHP 5.1.0
{
$obj = new A;
$obj->var1 = $an_array['var1'];
$obj->var2 = $an_array['var2'];
return $obj;
}
}
$a = new A;
$a->var1 = 5;
$a->var2 = 'foo';
eval('$b = ' . var_export($a, true) . ';'); // $b = A::__set_state(array(
// 'var1' => 5,
// 'var2' => 'foo',
// ));
var_dump($b);
?>
This will be helpful too.
You can fetch all properties using get_object_vars():
$vars = get_object_vars($car1);
foreach ($vars as $key => $value) {
echo $key . ' = ' . $value . '<br />';
}

Getting Array Data in php

I need to be able to get the data out of the following functions:
getStuff();
getRelateStuff();
getRelatedStuffInStuff();
Begin Code:
function getStuff()
{
return array("It", "Works");
}
function Stuff()
{
$value = array(getStuff());
foreach ($value as $key => $value)
{
echo "$key $value <br />\n";
}
}
function getRelatedStuff()
{
return array("hello" => "world", "cake"=> "is a lie");
}
function RelatedStuff()
{
$value = array(getRelatedStuff());
foreach ($value as $key => $value)
{
echo "$key $value <br />\n";
}
}
//Related in Stuff
function getRelatedStuffInStuff()
{
$s1 = array("hello" => "world", "cake"=> "is a lie");
$s2 = array("apple" => "mac", "microsoft"=> "windows", "linus" => "linux");
$s3 = array("OSX" => "10.6", "Ubuntu" => "11.04", "Windows" => "7");
return array($s1, $s2, $s3);
}
function RelatedInStuff()
{
$value = array(getRelatedStuffInStuff());
foreach ($value as $key => $value)
{
echo "$key $value <br />\n";
}
}
?>
When I try to view this page in a web browser it just shows a blank page. I am doing anything correctly? What should or what can I change?
If this is your full code... you have to call the functions.
Also your functions already return an array so you don't need to wrap those calls in array(...).
Try to add this at the end of your code (the ?> is the last line in what you posted):
?>
<html><body>
<?php
RelatedInStuff();
?>
</body></html>
This will actually generate some HTML and call one of your functions.

Categories