PHP: Cleanest way to modify multidimensional array?

phparraymultidimensionalmodifycleanestassociativesolved

Last Update : 2023-09-22 UTC 09:43:08 AM

Answers of > PHP: Cleanest way to modify multidimensional array?

edit: With one minor caveat: you need to call w3coded php modify toArray() on data representing an array, to w3coded php modify convert it to an array, as the class internally w3coded php modify needs to covert array data to an instance of w3coded php modify itself, to allow access with the object property w3coded php modify operator ->:,Asking for help, clarification, or w3coded php modify responding to other answers., w3coded php modify Use verb in -masu form + kana w3coded php modify to wonder about something instead of using the w3coded php modify -darou form ,I've w3coded php modify got a Config class in my application, which w3coded php modify loads static config settings and parses them w3coded php modify into arrays. As I need to override some elements w3coded php modify during runtime, I would need to access the w3coded php modify public variable inside the Config-class by doing w3coded php modify this; $config->values['onelevel']['twolevel'] = w3coded php modify 'changed';

Eh, that's not really necessary anymore of course, since it implements ArrayAccess now. ;-)
/edit

class Config
    implements ArrayAccess
{
    protected $_data;

    public function __construct( array $data )
    {
        foreach( $data as $key => $value )
        {
            $this->$key = $value;
        }
    }

    public function __get( $key )
    {
        return $this->offsetGet( $key );
    }

    public function __isset( $key )
    {
        return $this->offsetExists( $key );
    }

    public function __set( $key, $value )
    {
        $this->offsetSet( $key, $value );
    }

    public function __unset( $key )
    {
        $this->offsetUnset( $key );
    }

    public function offsetSet( $offset, $value )
    {
        $value = is_array( $value ) ? new self( $value ) : $value;

        if( is_null( $offset ) )
        {
            $this->_data[] = $value;
        }
        else
        {
            $this->_data[ $offset ] = $value;
        }
    }

    public function offsetExists( $offset )
    {
        return isset( $this->_data[ $offset ] );
    }

    public function offsetUnset( $offset )
    {
        unset( $this->_data[ $offset ] );
    }

    public function offsetGet( $offset )
    {
        return isset( $this->_data[ $offset ] ) ? $this->_data[ $offset ] : null;
    }

    public function toArray()
    {
        $array = array();
        $data = $this->_data;
        foreach( $data as $key => $value )
        {
            if( $value instanceof Config )
            {
                $array[ $key ] = $value->toArray();
            }
            else
            {
                $array[ $key ] = $value;
            }
        }
        return $array;
    }
}

edit 2:
The Config class can even be greatly simplified by extending ArrayObject. As an added benefit, you can cast it to a proper array also.

class Config
    extends ArrayObject
{
    protected $_data;

    public function __construct( array $data )
    {
        parent::__construct( array(), self::ARRAY_AS_PROPS );
        foreach( $data as $key => $value )
        {
            $this->$key = $value;
        }
    }

    public function offsetSet( $offset, $value )
    {
        $value = is_array( $value ) ? new self( $value ) : $value;

        return parent::offsetSet( $offset, $value );
    }
}

Example usage:

$configData = array(
    'some' => array(
        'deeply' => array(
            'nested' => array(
                'array' => array(
                    'some',
                    'data',
                    'here'
                )
            )
        )
    )
);
$config = new Config( $configData );
// casting to real array
var_dump( (array) $config->some->deeply->nested->array );

$config->some->deeply->nested->array = array( 'new', 'awsome', 'data', 'here' );
// Config object, but still accessible as array
var_dump( $config->some->deeply->nested->array[ 0 ] );

$config[ 'some' ][ 'deeply' ][ 'nested' ][ 'array' ] = array( 'yet', 'more', 'new', 'awsome', 'data', 'here' );
var_dump( $config[ 'some' ][ 'deeply' ][ 'nested' ][ 'array' ] );

$config[ 'some' ][ 'deeply' ][ 'nested' ][ 'array' ][] = 'append data';
var_dump( $config[ 'some' ][ 'deeply' ][ 'nested' ][ 'array' ] );

var_dump( isset( $config[ 'some' ][ 'deeply' ][ 'nested' ][ 'array' ] ) );

unset( $config[ 'some' ][ 'deeply' ][ 'nested' ][ 'array' ] );
var_dump( isset( $config[ 'some' ][ 'deeply' ][ 'nested' ][ 'array' ] ) );

// etc...

I too have had this problem, and I solved this with this code. However it was based on API like: Config::set('paths.command.default.foo.bar').

<?php

$name = 'paths.commands.default';
$namespaces = explode('.', $name);

$current = &$this->data; // $this->data is your config-array
foreach ( $namespaces as $space )
{
    $current = &$current[$space];
}
$current = $value;

This is a code example of an override function Demo:

$array = array(
   'a' => array( 'b' => array( 'c' => 'value') ),
   'b' => array( 'a' => 'value' ),
);

function override($array, $value) {
    $args = func_get_args();
    $array = array_shift($args);
    $value = array_shift($args);
    $set = &$array;
    while(count($args))
    {
        $key = array_shift($args);
        $set = &$set[$key];
    }
    $set = $value;
    unset($set);
    return $array;
}

var_dump(override($array, 'new', 'a', 'b', 'c'));

Some time ago I needed a function that would let me access an array through string path, maybe you can make use of that:

function PMA_array_write($path, &$array, $value)
{
    $keys = explode('/', $path);
    $last_key = array_pop($keys);
    $a =& $array;
    foreach ($keys as $key) {
        if (! isset($a[$key])) {
            $a[$key] = array();
        }
        $a =& $a[$key];
    }
    $a[$last_key] = $value;
}

Current topics : PHP: Cleanest way to modify multidimensional array?

Newly Added Questions

Similar Questions

Questions :

How To Group Array Key Value

Last Update : 2023-09-22 UTC 12:53:42 PM

Questions :

PhpStorm Warning For React Attributes In Jsx File With SCSS File

Last Update : 2023-09-22 UTC 12:53:36 PM

Questions :

Why Is The File Not Showing Up In Request.files And In Request.forms Instead?

Last Update : 2023-09-22 UTC 12:53:21 PM

Questions :

Proxying Assets From React App Directory In Slim Framework?

Last Update : 2023-09-22 UTC 12:53:15 PM

Questions :

Laravel 5.4 Can't Run “php Artisan Preset React” Comand

Last Update : 2023-09-22 UTC 12:52:58 PM

Questions :

How To Update Session Values Without Signing Out?

Last Update : 2023-09-22 UTC 12:52:50 PM

Questions :

Array Is Not Visible

Last Update : 2023-09-22 UTC 12:52:34 PM

Questions :

React Routing For Login Using Symfony

Last Update : 2023-09-22 UTC 12:52:28 PM

Questions :

Sanctum With React SPA Returning 419 Page Expired

Last Update : 2023-09-22 UTC 12:52:15 PM

Questions :

How Do I Import An Input String Into Another Page

Last Update : 2023-09-22 UTC 12:52:03 PM

Top
© 2023 W3CODED - All Rights Reserved.