开发者

How can I insert an item in the middle of an object in PHP?

开发者 https://www.devze.com 2023-04-13 09:16 出处:网络
If I have a stdClass object like the one below, which has three arrays with non-numeric keys, what\'s the best way to insert another item into the object between my-account and settings?

If I have a stdClass object like the one below, which has three arrays with non-numeric keys, what's the best way to insert another item into the object between my-account and settings?

[menu1] => stdClass Object
    (
        [my-account] => Array
            (
    开发者_运维问答            [title] => 'My Account'
                )
        [settings] => Array
            (
                [title] => 'Settings'
                )
        [payments] => Array
            (
                [title] => 'Payments'
                )
)


Create your own class for this with functions to add and remove items and their attributes. Then use some functions such as @genesis provided.


There's no function to do this. You'll have to do your own and rebuild your object

http://sandbox.phpcode.eu/g/fba96/3

<?php
function insert_after($var, $key, $value, $after){
    $new_object = array();
    foreach((array) $var as $k => $v){
       $new_object[$k] = $v;
       if ($after == $k){
           $new_object[$key] = $value;
       }
    }
    $new_object = (object) $new_object;
    return $new_object;
}

$var = insert_after($var, 'new dummy var between', array('title' => 'value'), 'my-account');


Add your item and then remove and re-add the items which ned to come after it:

$menu1->newitem = array('title'=>'Title');
$settings = $menu1->settings;

unset($menu1->settings);
$menu1->settings = $settings;
unset($settings);

unset($menu1->payments);
$menu1->payments = $payments;
unset($payments);
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号