Class com array php

Converting a PHP array to class variables

Simple question, how do I convert an associative array to variables in a class? I know there is casting to do an (object) $myarray or whatever it is, but that will create a new stdClass and doesn’t help me much. Are there any easy one or two line methods to make each $key => $value pair in my array into a $key = $value variable for my class? I don’t find it very logical to use a foreach loop for this, I’d be better off just converting it to a stdClass and storing that in a variable, wouldn’t I?

class MyClass < var $myvar; // I want variables like this, so they can be references as $this->myvar function __construct($myarray) < // a function to put my array into variables >> 

I believe this question is answered here. A loader method inside the class itself doesn’t seem to be a smart solution, since you’ll need to be extra careful about throwing exceptions and error handling specially inside the constructor.

7 Answers 7

This simple code should work:

$foo = new MyClass(array("hello" => "world")); $foo->hello // => "world" 

Alternatively, this might be a better approach

_data = $properties; > // magic methods! public function __set($property, $value)< return $this->_data[$property] = $value; > public function __get($property)< return array_key_exists($property, $this->_data) ? $this->_data[$property] : null ; > > ?> 
// init $foo = new MyClass(array("hello" => "world")); $foo->hello; // => "world" // set: this calls __set() $foo->invader = "zim"; // get: this calls __get() $foo->invader; // => "zim" // attempt to get a dataClass com array php that isn't set $foo->invalid; // => null 

@AntonioCS, it’s not necessary but it definitely emphasizes the access of a variable-named property. It also demonstrates that < >can be used when the variable property becomes more complex; e.g., $this->foo(‘bar’)>->do_something();

Читайте также:  When to escape html

+1. Should also mention that unless you make sure that the __get method returns a reference, using the magic methods with arrays might cause some minor issues (i.e $this->myArray[] = $value; will not work)

@Tobia In the first approach, yes: property_exists will return true only if the property has been explicitly defined in the class’ code. So you just define your properties as usual, then in the constructor’s foreach loop, you check if (property_exists(self::class, $key)) before assigning the property.

Best solution is to have trait with static function fromArray that can be used for data loading:

trait FromArray < public static function fromArray(array $data = []) < foreach (get_object_vars($obj = new self) as $property =>$default) < if (!array_key_exists($property, $data)) continue; $obj-> = $data[$property]; // assign value to object > return $obj; > > 

Then you can use this trait like that:

Then you can call static fromArray function to get new instance of Example class:

$obj = Example::fromArray(['data' => 123, 'prop' => false]); var_dump($obj); 

I also have much more sophisticated version with nesting and value filtering https://github.com/OzzyCzech/fromArray

Instead of using get_object_vars($obj = new self , you can just say get_class_vars(get_class($this)) — no need to create a dummy object.

@Meglio actually, it’s not a dummy object, it’s the instance that will end up being returned after setting the properties. If get_class($this) or the alternative self::class are used, you’d have to create an instance before the loop.

if you (like me) came here looking for a source code generator for array->class, i couldn’t really find any, and then i came up with this (a work in progress, not well tested or anything, json_decode returns the array.):

,"commits":[,"added":[],"modified":["gitlab_callback_page.php"],"removed":[]>],"total_commits_count":1,"repository":> JSON; $arr = json_decode ( $json, true ); var_dump ( array_to_class ( $arr ) ); /** * * @param array $arr * @param string $top_class_name */ function array_to_class(array $arr, string $top_class_name = "TopClass"): string < $top_class_name = ucfirst ( $top_class_name ); $classes = array (); // deduplicated 'definition'=>true,array_keys(); $internal = function (array $arr, string $top_class_name) use (&$classes, &$internal) < $curr = 'Class ' . $top_class_name . ' $val ) < $type = gettype ( $val ); if (is_array ( $val )) < $type = ucfirst ( ( string ) $key ); $classes [$internal ( $val, ( string ) $key )] = true; >$curr .= $curr .= '>'; $classes [$curr] = true; >; $internal ( $arr, $top_class_name ); return implode ( "\n", array_keys ( $classes ) ); > 
Class project < /** * @property string $name */ public $name; /** * @property string $description */ public $description; /** * @property string $web_url */ public $web_url; /** * @property NULL $avatar_url */ public $avatar_url; /** * @property string $git_ssh_url */ public $git_ssh_url; /** * @property string $git_http_url */ public $git_http_url; /** * @property string $namespace */ public $namespace; /** * @property integer $visibility_level */ public $visibility_level; /** * @property string $path_with_namespace */ public $path_with_namespace; /** * @property string $default_branch */ public $default_branch; /** * @property string $homepage */ public $homepage; /** * @property string $url */ public $url; /** * @property string $ssh_url */ public $ssh_url; /** * @property string $http_url */ public $http_url; >Class author < /** * @property string $name */ public $name; /** * @property string $email */ public $email; >Class added < >Class modified < /** * @property string $0 */ public $0; >Class removed < >Class 0 < /** * @property string $id */ public $id; /** * @property string $message */ public $message; /** * @property string $timestamp */ public $timestamp; /** * @property string $url */ public $url; /** * @property Author $author */ public $author; /** * @property Added $added */ public $added; /** * @property Modified $modified */ public $modified; /** * @property Removed $removed */ public $removed; >Class commits < /** * @property 0 $0 */ public $0; >Class repository < /** * @property string $name */ public $name; /** * @property string $url */ public $url; /** * @property string $description */ public $description; /** * @property string $homepage */ public $homepage; /** * @property string $git_http_url */ public $git_http_url; /** * @property string $git_ssh_url */ public $git_ssh_url; /** * @property integer $visibility_level */ public $visibility_level; >Class TopClass < /** * @property string $object_kind */ public $object_kind; /** * @property string $event_name */ public $event_name; /** * @property string $before */ public $before; /** * @property string $after */ public $after; /** * @property string $ref */ public $ref; /** * @property string $checkout_sha */ public $checkout_sha; /** * @property NULL $message */ public $message; /** * @property integer $user_id */ public $user_id; /** * @property string $user_name */ public $user_name; /** * @property string $user_email */ public $user_email; /** * @property string $user_avatar */ public $user_avatar; /** * @property integer $project_id */ public $project_id; /** * @property Project $project */ public $project; /** * @property Commits $commits */ public $commits; /** * @property integer $total_commits_count */ public $total_commits_count; /** * @property Repository $repository */ public $repository; >

Источник

Create an array inside a class with php

I have a class and I need to build an array. I usually can do that with a query and looping that but I am not sure how to do that with a class. Do I create the array before hand and turn it into a string? Here is my code sample

/** My Setting class **/ if ( ! class_exists( 'WC_my_setting' ) ) < class WC_my_setting < public function __construct() < // Init settings $this->settings = array( array( 'name' => __( 'My Setting', 'woocommerce-my-setting' ), 'type' => 'title', 'id' => 'wc_my_setting_options' ), array( 'name' => __( 'Name', 'woocommerce-my-setting' ), 'id' => 'wc_my_setting_category', 'type' => 'multiselect', //I want to have this->settings[options] populated with the array that the $category_options makes. 'options' => $category_options ), ) ), array( 'type' => 'sectionend', 'id' => 'woocommerce-my-setting' ), ); // Default options add_option( 'wc_my_setting_category', '' ); // Admin add_action( 'woocommerce_settings_image_options_after', array( $this, 'admin_settings' ), 20 ); add_action( 'woocommerce_update_options_catalog', array( $this, 'save_admin_settings' ) ); add_action( 'woocommerce_update_options_products', array( $this, 'save_admin_settings' ) ); > 

I can the code below on page templates just fine and I can output the array fine but I cannot get this working in the class in the admin area:

$categories = get_terms( 'product_cat', 'orderby=name&hide_empty=0' ); $category_options = array(); if ( $categories ) < foreach ( $categories as $cat ) < $category_options[ $cat->slug ] = $cat->name; > > // print_r($category_options); 

How do I get the above loop in my class so the $category_options is placed in the $this->settings[options]

Источник

Convert stdClass object to array in PHP [duplicate]

The easiest way is to JSON-encode your object and then decode it back to an array:

$array = json_decode(json_encode($object), true); 

Or if you prefer, you can traverse the object manually, too:

foreach ($object as $value) $array[] = $value->post_id; 

@akshaynagpal: It’d result in an error because you’ll be giving an object to a function that expects a JSON string as its input. In the answer, I am converting the object to a JSON string, and then feeding it as an input to json_decode() so it would return an array (the second parameter being as True indicates an array should be returned).

@chhameed: Typecasting won’t work if your object has other objects nested inside it. See example — eval.in/1124950

Very simple, first turn your object into a json object, this will return a string of your object into a JSON representative.

Take that result and decode with an extra parameter of true, where it will convert to associative array

$array = json_decode(json_encode($oObject),true); 
$new_array = objectToArray($yourObject); function objectToArray($d) < if (is_object($d)) < // Gets the properties of the given object // with get_object_vars function $d = get_object_vars($d); >if (is_array($d)) < /* * Return array converted to object * Using __FUNCTION__ (Magic constant) * for recursive call */ return array_map(__FUNCTION__, $d); >else < // Return array return $d; >> 

You can convert an std object to array like this:

$objectToArray = (array)$object; 

This is great, but it converts only the first level. If you have nesting you have to do it for all nodes.

There are two simple ways to convert stdClass Object to an Array

$array = get_object_vars($obj); 
$array = json_decode(json_encode($obj), true); 

or you can simply create array using foreach loop

$array = array(); foreach($obj as $key) < $array[] = $key; >print_r($array); 

For one-dimensional arrays:

For multi-dimensional array:

While converting a STD class object to array.Cast the object to array by using array function of php.

Try out with following code snippet.

/*** cast the object ***/ foreach($stdArray as $key => $value) < $stdArray[$key] = (array) $value; >/*** show the results ***/ print_r( $stdArray ); 

This will convert the outer object to an array, but if any of the properties are also objects they won’t be converted.

As per the OP’s question he has one level of object structure. For next levels you have to add another foreach loop.

$wpdb->get_results("SELECT . ", ARRAY_A); 

ARRAY_A is a «output_type» argument. It can be one of four pre-defined constants (defaults to OBJECT):

OBJECT - result will be output as a numerically indexed array of row objects. OBJECT_K - result will be output as an associative array of row objects, using first columns values as keys (duplicates will be discarded). ARRAY_A - result will be output as an numerically indexed array of associative arrays, using column names as keys. ARRAY_N - result will be output as a numerically indexed array of numerically indexed arrays. 

Источник

Using Array in PHP Class

I am exercising some PHP OOP and therefore I am creating a class to create a simple navigation menu ( with extensions in the future ) now I have build this class that works kinda.. with 1 menu item tough.. I don;t know how to use arrays in my class to use the class like

setMenuItem("home", "test"); echo $menu->display(); ?> 

as you see I should be able to give each menu item with the setMenuItem(); method. but since it does not use Arrays at the moment I only get the first value The class itself is as follows:

who can show me how to use arrays within the class in combination with a loop to create a menu with all given values? Thanks in advance.

4 Answers 4

You actually have two types, not one:

The MenuItemList would take care of managing the list. It could use an array internally. A code example for something very similar could be found in a previous answer: Array Object In Php.

Next to that the display() method does not belong into the two. Instead you should make your template that keen it knows how to output a menu list:

echo '
    '; foreach ($menu as $item) < echo '
    )" data-controller="se-share-sheet" data-se-share-sheet-title="Share a link to this answer" data-se-share-sheet-subtitle="" data-se-share-sheet-post-type="answer" data-se-share-sheet-social="facebook twitter devto" data-se-share-sheet-location="2" data-se-share-sheet-license-url="https%3a%2f%2fcreativecommons.org%2flicenses%2fby-sa%2f3.0%2f" data-se-share-sheet-license-name="CC BY-SA 3.0" data-s-popover-placement="bottom-start">Share
    )" title="">Improve this answer
    )">edited May 23, 2017 at 10:26
    CommunityBot
    11 silver badge
    answered Nov 4, 2012 at 17:31
2
    What about MenuItemList::__toString()?
    – Madara's Ghost
    Nov 4, 2012 at 17:33
    @MadaraUchiha: That could output a plain-text representation for debugging purposes. However you could create a HTML decorator for that menulist that would output a HTML list with it's __toString() method. But the menuitems should not care about how they are output in specific. That's the job of some other part of the code.
    – hakre
    Nov 4, 2012 at 17:34
Add a comment|
0

At top of your class

$menuItems = array();
function setMenuItem($name, $value) < $this->menuItems[] = array($name, $value); > 

Edit: You could change the way they are stored, and prevent duplicates by using the nav "Name" as the key it is stored under, but I've kept it simple for ease of understanding.

Heres a more advanced sample

function setMenuItem($name, $value) < if(!in_array(array_keys($this->menuItems)), $name) < $this->menuItems[$name] = $value; > else < echo "That's already been added!"; //Handle this properly though >> 

Источник

Оцените статью