i'm not good at using objects. And i'm working on using objects instead of arrays.
I have a code as array
$jsonData['overstockid'][] = $productid;
How can i write this as object ?
I defined jsonData
$jsonData = new \stdClass();
i know i can write $jsonData->overstockid
Set the overstockid property to an array, and then add to it:
$jsonData->overstockid = array();
$jsonData->overstockid[] = $productid;
A quick but nasty workaround to convert an array to an object is to use json_encode() and json_decode().
Example
$array = array(
'id' => 123,
'sub_id' => 456,
'gender' => 1,
'name' => 'John Doe',
'age' => 960,
);
$object = json_decode(json_encode($array));
Hope this helps.
Related
I'm developing with DataTables in Laravel and trying to make an object manually using collect() to create a collection. When I push the collection into the DataTable, there is something wrong, and I can't call my object with this $object->attribute.
After I get the error with that, I already tried to call an attribute with $object['attribute'], and it works well.
Can someone give me insight about the differences and how I can convert $object['attribute'] into $object->attribute?
This is my query to create object
$result = collect();
$item = collect([
'row' => ($key+1),
'item_id' => $value->uid,
'item' => $value->nama_item,
'sub_kategori' => $value->sub_jenis_item->sub_jenis_item,
'kategori' => $value->jenis_item->jenis_item,
'gudang_id' => $id_gudang
]);
$result->push($item);
Accessing $object['attribute'] means $object is an array and accessing $object->attribute means $object is an object.
To convert array to object:
$object = (object) $object;
Additionally, to convert object to array:
$object = (array) $object;
DataTables calls internally toArray() on the collection items when you build the table. This happens during transformation of the data. It will also flatten nested objects (e.g. loaded Eloquent relations in case of an EloquentDataTable) into an array with depth 1 (per row of the table).
You can try the following way,
$result = collect();
$item = collect([
'row' => ($key+1),
'item_id' => $value->uid,
'item' => $value->nama_item,
'sub_kategori' => $value->sub_jenis_item->sub_jenis_item,
'kategori' => $value->jenis_item->jenis_item,
'gudang_id' => $id_gudang
]
);
$result->push($item);
$resultObj = json_decode($result);
foreach($resultObj as $obj){
echo $obj->row;
}
I have this array
$data = array(
'employer' => $employer,
'manager' => $manager
);
my intention is access the array as an object, like: $data->employer.
How can i do that?
You can typecast an array to object like so:
<?php
$data = array(
'employer' => "employer",
'manager' => "manager "
);
$object = (object) $data;
var_dump($object->employer); // => "employer"
The returned value will be an instance of \stdClass, as described in the documentation.
Currently my JSON outputs from the following PHP:
$data['products'][] = array(
'product_id' => $result['product_id'],
'thumb' => $image,
'name' => $result['name'],
'description' => $desc,
'price' => $price,
'special' => $special,
'tax' => $tax,
);
And with this ($products = json_encode ($data['products']);) produces the following:
[{"product_id":"28",
"thumb":"x",
"name":"name",
"description":"abc",
"price":"$123.00",
"special":false,
"tax":"$100.00"}]
Is it possible to delete the names without modifying the php "$data['products'][] = array();"? I am trying to achieve:
["28",
"x",
"name",
"abc",
"$123.00",
false,
"$100.00"]
First time ever using JSON encode so any other advice would be awesome!
You can use array_map to loop thru your array and use array_values as callback function to convert the associative array to simple array
$arr = array_map('array_values', $data['products'] );
$products = json_encode ($arr);
This will result to:
[["28","x","name","abc","$123.00",false,"$100.00"]]
Live Example
You can use array_values to get the values of the first/only entry in $data['products'], and then encode that:
$json = json_encode(array_values($data['products'][0]));
That produces
["28","x","name","abc","$123.00",false,"$100.00"]
Live Example
Each of my users has a JSON encoded string saved to a field called 'json'. There will be multiple multidimensional items but nutrients will not always be an element. This is the format:
$arr = array(
0 => array(
'name' => Input::get('name'),
'amount' => 5,
'time' => '2:00 am',
'nutrients' => array(
'Macro' => array(
'water' => 0,
'carbs' => 0,
),
'Micro' => array(
'zinc' => 0,
)
)
);
$user->json = json_encode($arr);
$user->save();
I want to (in another view) convert $user->json into a CSV file. This is the closest I could get with code I found online but I still get an error ('fputcsv() expects parameter 2 to be array, object given'):
$user = Auth::user();
$json_obj = json_decode ($user->json);
$fp = fopen('file.csv', 'w');
foreach ($json_obj as $fields) {
fputcsv($fp, $fields);
}
fclose($fp);
If I use $json_obj = json_decode ($user->json, true); I get the error "Array to string conversion"
Any help is appreciated, let me know if more information is needed. Thank you!
Well you got arrays in your array... thats why you get the error when you're doing the json_decode($data, true). You got to decide how you want to format your other data like "nutrients".
I hope you get the point. The problem is that it expects an array of primitive data and not an array with another array in it.
I am using PHP and trying to create an array that looks something like this:
{
"aps" : {
"alert" : "Hey"
},
"custom_control" : {
"type" : "topic_comment",
"object":{
"topic_id":"123",
"topic_section":"test"
"plan_id":"456"
}
}
}
So far I have something like
$message = array('aps'=>array('alert'=>$some_variable));
but I am getting confused how I can put the values for "custom_control" into this array after that. Could anyone please advise how to do that from my existing php?
Thanks!
Is this what you mean?
<?php
$some_variable = "Hey";
$myArray = array(
"aps" => array(
"alert" => $some_variable
),
"custom_control" => array(
"type" => "topic_comment",
"object" => array(
"topic_id" => "123",
"topic_section" => "test",
"plan_id" => "456"
)
)
);
?>
Here is an easy way to discover what you need to do.
Create your JSON object.
Use it as input to the json_decode function.
Use the output of this as the input to var_export()
So supposing you assigned your JSON to $json_object, then use:
var_export(json_decode($json_object, true));
If you are more comfortable building the object in JSON you can use the JSON parser included in php. Also, JSON defines Javascript objects, not arrays (although you can define arrays in JSON with something like {myArray : [1,2,3]}
Try this if you want though:
http://php.net/manual/en/function.json-decode.php
If you've already created your initial message array (per your question), you would then do something like this.
$message["custom_control"] = array(
"type" => "topic_comment",
"object" => array(
"topic_id" => "123",
"topic_section" => "test",
"plan_id" => "456"
)
)
You can create whatever nodes you needs inside of $message this way.
What you are trying to create is not an array, but rather an object.
Try to not build it as an array but an object.
$obj = new stdClass();
$obj->aps = new stdClass();
$obj->aps->alert = 'Hey';
$obj->custom_control = new stdClass();
$obj->custom_control->type = 'topic_comment';
$obj->custom_control->object = new stdClass();
$obj->custom_control->object->topic_id = '123';
$obj->custom_control->object->topic_section = 'test';
$obj->custom_control->object->plan_id = '456';
$json = json_encode($obj);
$array = array();
$array['aps'] = "alert";
$array['custom_control'] = array();
$array['custom_control']['type'] = "topic_comment";
$array['custom_control']['object'] = array('topic_id' => '123',
'topic_section' => 'test',
'plan_id' => '456');
i think you need something like this:
$message =array( "aps" =>array("alert"=>"Hey"),
"custom_control" => array(
"type" => "topic_comment",
"object" => array(
"topic_id"=>"123",
"topic_section"=>"test",
"plan_id"=>"456"
)
)
);