开发者

Add child node to a specific index in an object with php

开发者 https://www.devze.com 2023-01-06 06:37 出处:网络
I have an object, and I have a new value which I need to add to this object, but not just to the end of it, that would be no problem accomplishing. What I need to do is add this value to a new node on

I have an object, and I have a new value which I need to add to this object, but not just to the end of it, that would be no problem accomplishing. What I need to do is add this value to a new node on a specific index.

Ok so here's the object.

[object]=>{ 
  ["a"]=> "value" 
  ["b"]=&开发者_如何学Pythongt; "value" 
  ["c"]=> "value"
  ["d"]=> "value"
} 

Then I have this fifth value that I now need to add to index 1, or as it's named in this example "b". Like this.

[object]=>{ 
  ["a"]=> "value"
  ["e"]=> "fifth value"
  ["b"]=> "value" 
  ["c"]=> "value"
  ["d"]=> "value"
} 

So the question remains, is there a smart way to do this or do I have to split them up and make them into arrays and merge them as arrays then assign them to a new object explicitly telling it to be an object?

Like this.

$object = (object)array_merge((array)$first, (array)$second);

I feel that there must be a better way to handle this, with only objects.

Thank you for your time.


What are you doing that needs this:

[object]=>{ 
  ["a"]=> "value"
  ["e"]=> "fifth value"
  ["b"]=> "value" 
  ["c"]=> "value"
  ["d"]=> "value"
} 

to be different from this:

[object]=>{ 
  ["a"]=> "value"
  ["b"]=> "value" 
  ["c"]=> "value"
  ["d"]=> "value"
  ["e"]=> "fifth value"
} 

?

If you NEED them to be different, you are using OOP wrong.

EDIT: What's stopping you from using arrays?


Objects simply don't have indexes, they have properties, and $obj->property is always $obj->property - no ordering, no indexes nothing like that.

What you need here is (generally) a numerically indexed array, not an object, and not an associative array - if you insist you need an alpha sorted associative array (alpha keys rather than numerical keys) then you can use ksort to handle this particular problem.

$array = array( 
  "a" => "value",
  "e" => "fifth value",
  "b" => "value",
  "c" => "value",
  "d" => "value",
);
ksort($array);
print_r($array);

note you can always turn it in to an object if for some reason you need this by doing $obj = (object)$array; after the sort

0

精彩评论

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