Changing object into array - php

I tried to change an object into array but seems like it doesn't work this way. Could someone tell me what to do in this case?
$blockedNumber = DB::select('SELECT COUNT(*) AS number FROM users_blocked WHERE (f_block = ? OR f_chat_block = ? OR f_hide_posts = ?)', array(1, 1, 1));
$number = (array) $blockedNumber;
var_dump($number[0]['number']);
var_dump shows me "Cannot use object of type stdClass as array"

From your reply, you can do this, and it will solve it.
$blockedNumber = DB::select('SELECT COUNT(*) AS number FROM users_blocked WHERE (f_block = ? OR f_chat_block = ? OR f_hide_posts = ?)', array(1, 1, 1));
$number = (array) $blockedNumber[0];
var_dump($number['number']);
Try it out.
If you need explanation let me know, I'll explain the reason. But, first check if its working.

$obj = new stdClass();
$objB = new stdClass();
$objB->deepFoo = 'bar';
$obj->bla = array(1,2,3,$objB);
$obj->blub = new stdClass();
$obj->blub->foo = 'bar';
function rekursiveObjectToArray($obj){
if(is_object($obj)){
$obj = (array)$obj;
}
if(is_array($obj)){
$obj = array_map('rekursiveObjectToArray',$obj);
}
return $obj;
}
$obj = rekursiveObjectToArray($obj);
var_dump($obj);

Related

Unsetting properties in array of objects where parent is a clone

I need to clone an object, then remove some properties from the clone. Using unset() on the cloned object works fine, but not on the cloned objects array of objects. I have simplified the object as it has quite a few more properties but the premise is the same.
$testobject = new stdClass();
$testobject->propertya = 'banana';
$testobject->propertyb = 'orange';
$testobject->propertyc = 'apple';
$testobject->childarray = array();
$testobject->childarray[] = new stdClass();
$testobject->childarray[0]->childpropertya = 'cola';
$testobject->childarray[0]->childpropertyb = 'bread';
$testobject->childarray[0]->childpropertyc = 'pasta';
echo "Original object:\n";
print_r($testobject);
$cloneobject = clone $testobject;
unset($cloneobject->propertyb);
foreach ($cloneobject->childarray as $index => $data) {
unset ($data->childpropertya);
}
unset($cloneobject->childarray['childpropertyc']);
echo "Original object expected to be the same but is NOT!:\n";
print_r($testobject);
I expect the $testobject not to change, but it does. Why?!
I have re-created the format in a 3v4l here
Solved, thanks for the tip #nice_dev
$testobject = new stdClass();
$testobject->propertya = 'banana';
$testobject->propertyb = 'orange';
$testobject->propertyc = 'apple';
$testobject->childarray = array();
$testobject->childarray[] = new stdClass();
$testobject->childarray[0]->childpropertya = 'cola';
$testobject->childarray[0]->childpropertyb = 'bread';
$testobject->childarray[0]->childpropertyc = 'pasta';
echo "Original object \n";
print_r($testobject);
$cloneobject = unserialize(serialize($testobject));
unset($cloneobject->propertyb);
foreach ($cloneobject->childarray as $index => $data) {
unset ($data->childpropertya);
}
unset($cloneobject->childarray['childpropertyc']);
echo "Original object is the same!\n";
print_r($testobject);
echo "Copied object is now different than $testobject!\n";
print_r($cloneobject);

PHP array_merge return null in class

Why this code return null?
I check it but there is no error, And when i am call array merge with 2 default array Like ["x"=>"y","foo"=>"bar"] it work well!
See:
<?php
class ClassName
{
private $dataArray = array();
public function put($arr){
$this->dataArray = array_merge($arr,$this->dataArray);
return $this;
}
public function run(){
echo json_encode($this->dataArray);
}
}
$json = new ClassName();
$json->Test->LastLog = '123456789123456';
$json->Password = 'Mypassword';
$json->Dramatic = 'Cat';
$json->Things = array("HI" => 1, 2, 3);
$json->put($json)->run();
You Passed an object not array try like this code you got result:
$json->put((array)$json)->run();
Output is:
> {"\u0000ClassName\u0000dataArray":["Volvo XC90","BMW
> M4","MaclarenP1"],"Test":"123456789123456","Password":"Mypassword","Dramatic":"Cat","Things":{"HI":1,"0":2,"1":3},"0":"Volvo
> XC90","1":"BMW M4","2":"MaclarenP1"}
EDIT
If you want to pass the $json->Test->LastLog like this means you need to alternate you object declaration like:
$json = new ClassName();
$json->Test = array('LastLog'=>'123456789123456');
$json->Password = 'Mypassword';
$json->Dramatic = 'Cat';
$json->Things = array("HI" => 1, 2, 3);
Because in your put function is array_merge expecting array but you sent a json_object instead of array. (array) is act like json_decode...
Example: Simple Object
$object = new StdClass;
$object->foo = 1;
$object->bar = 2;
var_dump( (array) $object );
Output:
array(2) {
'foo' => int(1)
'bar' => int(2)
}

Add property to stdClass at the top of the object in php

When creating a object in php used to return JSON is it possible to add a property and force it to go at the top? I'd like this since the object is exposed via an API and it is nice to have ids at the top.
For example:
$obj = new stdClass();
$obj->name = 'John';
$obj->age = 26;
$obj->id = 3645;
When you json_encode() this, it turns into:
{
"name": "John",
"age": 26,
"id": 3645
}
Is there a way to force id at the top of the object even though it is added last? Note, I can't simply just add id before adding name and age because of other dependent code.
It's easily possible if you use an associative array instead of an object, i.e.
$x = ['name' => 'john', 'age' => 26]; // or: $x = (array)$obj
$x = ['id' => 123] + $x;
echo json_encode($x);
// {"id":123,"name":"john","age":26}
However, it's important to note that in JSON property ordering is not defined and should not be relied upon. If what you currently have works, this change would be rather useless in fact.
Not very elegant but...
$obj = new stdClass();
$obj->name = 'John';
$obj->age = 26;
$obj->id = 3645;
$name = $obj->name;
$age = $obj->age;
unset($obj->name);
unset($obj->age);
$obj->name = $name;
$obj->age = $age;
echo json_encode($obj);
Hmm, nice question!
It is not possible to add a property and force it to go at the top.
You have to sort the object properties or the array keys.
Some nitpicking here: JSON is unordered by definition, but the browsers respect the insertion order. More: https://code.google.com/p/v8/issues/detail?id=164
JSON
4.3.3 Object An object is a member of the type Object. It is an unordered collection of properties each of which contains a
primitive value, object, or function. A function stored in a property
of an object is called a method.
Check this out: http://ideone.com/Hb4rGQ
<?php
function array_reorder_keys($array, $keynames){
if(empty($array) || !is_array($array) || empty($keynames)) return;
if(!is_array($keynames)) $keynames = explode(',',$keynames);
if(!empty($keynames)) $keynames = array_reverse($keynames);
foreach($keynames as $n){
if(array_key_exists($n, $array)){
$newarray = array($n=>$array[$n]); //copy the node before unsetting
unset($array[$n]); //remove the node
$array = $newarray + array_filter($array); //combine copy with filtered array
}
}
return $array;
}
$obj = new stdClass();
$obj->name = 'John';
$obj->age = 26;
$obj->id = 3645;
function get_json_sorted($object, $array) {
return json_encode(array_reorder_keys(get_object_vars($object), $array));
}
var_dump(get_json_sorted($obj, array('id', 'name', 'age')));
This is a solution. Turn the object into an assoc array. Get the last item (both key and value) off of the array (I'm assuming id is the last element) and move it to the front. Finally convert the assoc array back into an object.
$data_array = json_decode(json_encode($obj), true);
if(is_array($data_array)) {
end($data_array);
$data_array = array_merge(array(key($data_array) => array_pop($data_array)), $data_array);
$data = json_decode(json_encode($data_array), false);
}
This is a similar answer to Jacks' answer ( https://stackoverflow.com/a/24900322/6312186 ) but that caused a fatal error for me. I had to tweak it a bit by casting to array, using array_merge() and cast back to object, but this worked nicely for me:
$obj = (object) array_merge( (array)$obj2, (array)$obj);
This code is more generic and should work for all versions of PHP, including strict mode. Full code here
$obj = new stdClass(); // create new object
$obj->name = 'john';
$obj->age = '26';
$obj2 = new stdClass(); // we want to add this object to the top of $obj
$obj2->id = 'uid2039';
$obj = (object) array_merge( (array)$obj2, (array)$obj);
var_dump($obj);
// object(stdClass)#8700 (3) { ["id"]=> string(7) "uid2039" ["name"]=> string(4) "john" ["age"]=> string(2) "26" }
If you are json_encodeing this, you don't need to cast it back to an object again before encoding it:
$arr = ['name' => 'John', 'age' => '26'];
echo json_encode($arr);
// {"name":"john","age":"26"}
// is the same as:
$obj = (object)$arr;
echo json_encode($obj );
// {"name":"john","age":"26"}

PHP alternative way of writing stdClass

When doing stdClass in PHP we can do it this way:
// Create new stdClass Object
$init = new stdClass;
// Add some test data
$init->foo = "Test data";
$init->bar = new stdClass;
$init->bar->baaz = "Testing";
$init->bar->fooz = new stdClass;
$init->bar->fooz->baz = "Testing again";
$init->foox = "Just test";
Is there any other alternative way to do with so that it looks cleaner like we can do with JavaScript?
Thanks.
$array = array('x'=>123);
$object = (object) $array;

array to string conversion return error of stdClass

if($stmt->execute()){
$user = $stmt->get_result();
while ($obj = $user->fetch_object()) {
$result[] = $obj;
}
}
$result1encoded = json_encode($result);
echo $result1encoded;
// [{"uId":"1","firstName":"John"}]
I used implode like this :
echo $result1encoded = implode(' ',$result1);
// expecting '[{"uId":"1","firstName":"John"}]'
But it says
Object of class stdClass could not be converted to string
You can use array_map("json_encode", $your_array) to first convert each element of the array to string, and then use implode to glue it together.
See this https://eval.in/141541
<?php
$a = array();
$a[0] = new stdClass();
$a[0]->uId = "1";
$a[0]->firstName = "John";
$a[1] = new stdClass();
$a[1]->uId = "2";
$a[1]->firstName = "Albert";
$b = array_map("json_encode", $a);
echo implode(' ', $b);
?>
To convert Array to String you can use serialize() method like this
$result1encoded = json_encode($result);
echo serialize($result1encoded);
Another Way to do is
$result1encoded = json_encode($result);
echo $result1 = implode(' ',$result1encoded);
|**Edited Part**|
Please go through flowing link hope it solves ur problem
Array to String Conversions

Categories