How to push an object to laravel db? [duplicate] - php

This question already has answers here:
In PHP how can I access a ":private" array in an object?
(3 answers)
Convert a PHP object to an associative array
(33 answers)
Closed 5 years ago.
I'm working with Laravel, and I have an Object that I must push to my DB, the thing is, this is an Object, and I need it to be an array to push it in, Ill explain here:
so, this is how Im pushing in the array to my DB:
$subset = collect($MYARRAY);
$arr = $subset->map (function ($item) {
$now = Carbon::now('utc')->toDateTimeString();
return array(
'order_id' => $item['data']['AmazonOrderId'],
'buyer_name' => $item['data']['BuyerName'],
'buyer_email' => $item['data']['BuyerEmail'],
'store_name' => $item['storeName'],
'ship_service_level' => $item['data']['ShipServiceLevel'],
'order_status' => $item['data']['OrderStatus'],
'fulfillment_channel' => $item['data']['FulfillmentChannel'],
'purchase_date' => $item['data']['PurchaseDate'],
'last_ship_date' => $item['data']['LatestShipDate'],
'created_at'=> $now,
'updated_at'=> $now
);
})->all();
$order->insert($arr);
This code is working great, If I have this $MYARRAY (I created the array manually):
$MYARRAY = array (
0 =>
array(
'data' =>
array (
[AmazonOrderId] => 111
[SellerOrderId] => 222
[PurchaseDate] => 2013-05-31T15:20:59Z
[LastUpdateDate] => 2013-06-01T18:00:41Z
...
))
1 =>
array(
'data' =>
array (
...
)
);
But, it fails in this object (this is var_export of the object):
Array
(
[0] => Sonnenglas\AmazonMws\AmazonOrder Object
(
[data:Sonnenglas\AmazonMws\AmazonOrder:private] => Array
(
[AmazonOrderId] => 111
[SellerOrderId] => 222
[PurchaseDate] => 2013-05-31T15:20:59Z
[LastUpdateDate] => 2013-06-01T18:00:41Z
...
)
)
[1] => Sonnenglas\AmazonMws\AmazonOrder Object
(
[data:Sonnenglas\AmazonMws\AmazonOrder:private] => Array
(
[AmazonOrderId] => 2345
[SellerOrderId] => 2345
[PurchaseDate] => 2013-06-01T02:11:24Z
...
))
Now, this is what I have tried, I tried to convert it to array like that:
$array = json_decode(json_encode($object), true);
but then I had an empty arrays (the conversion to json and back deleted it all because of the object type I guess).
I have tried this one as well:
$MYARRAY = array_map(function($object){
return (array) $object;
}, $data);
With no success, (I have tried also to cast it to array with foreach) so, can you please help, how can I convert this object back to array, or, how can I map the object to push it in the DB?
Thank you!

Related

Convert a json to multi-dimensional PHP array

I have the following json sent to my API endpoint
{"key":"levels","value":"[{role_id:1, access_level_id:3}, {role_id:2, access_level_id:1}, {role_id:3, access_level_id:2}]","description":""}
at the backend, I receive it as a Laravel request as follows:
public function functionName(Request $request){
$req=$request->all();
Log::debug($req['value']);
return;
}
And it returns the following expected result
array (
'key' => 'levels',
'value' => '[{role_id:1, access_level_id:3}, {role_id:2, access_level_id:1}, {role_id:3, access_level_id:2}]',
'description' => NULL,
)
But I need to convert the 'value' to array also. so that I can have a multidimensional PHP array. So I expect to get something like
array (
'key' => 'levels',
'value' => array(
array('role_id'=>1, 'access_level_id'=>3),
array('role_id'=>2, 'access_level_id'=>1),
array('role_id'=>3, 'access_level_id'=>2)
)
'description' => NULL,
)
but when in my Laravel method I do the following:
public function share_doc(Request $request){
$req=$request->all();
Log::debug(json_decode($req['value'],true));
return;
}
trying to convert the json received as 'value' to PHP array, it returns nothing -i.e. no value, no array, no string. Just nothing.
So, my struggle here is how I can convert the entire json string received as 'value' from the request to a PHP array so that I can iterate through the items with PHP
Thank you for helping
Your problem is that the value element is not valid JSON as the keys are not quoted. For the sample data you provide, you can fix that with preg_replace and then json_decode the changed value:
$x['value'] = json_decode(preg_replace('/(\w+)(?=:)/', '"$1"', $x['value']), true);
print_r($x);
Output:
Array
(
[key] => levels
[value] => Array
(
[0] => Array
(
[role_id] => 1
[access_level_id] => 3
)
[1] => Array
(
[role_id] => 2
[access_level_id] => 1
)
[2] => Array
(
[role_id] => 3
[access_level_id] => 2
)
)
[description] =>
)
Demo on 3v4l.org

Pushing values into multidimensional array [duplicate]

This question already has answers here:
PHP add elements to multidimensional array with array_push
(4 answers)
Closed 2 years ago.
I'm already getting below array results as follows. All I wanted is to add more entries in it.
How do I do that?
Array
(
[result] => Array
(
[0] => Array
(
[number] => AAA1222
[short_description] => User unable to print
[state] => Closed
)
[1] => Array
(
[number] => AAA1223
[short_description] => Share drive not accessible
[state] => Closed
)
[2] => Array
(
[number] => AAA1224
[short_description] => Network is down
[state] => Closed
)
)
)
If I wanted to add more entries to the array like
[number] => AAA1225
[short_description] => Cable replacement on workstation 12
[state] => Closed
How do I accomplish that.
Thanks!!
You can try with array_push() function too.
Your existence array:
$myArr['result'] = [........]
New array values
$data['number'] = 'AAA1224';
$data['short_description'] = 'Network is down';
$data['state'] = 'Closed';
Push new array into existance array:
array_push($myArr['result'],$data);
Considering you are storing above array in a variable named as $arr.
$arr = [ ... ]; // contains your existing data.
// To add new data
$arrNewData = [
'number' => 'AAA1225',
'short_description' => 'Cable replacement on workstation 12',
'state' => 'Closed'
];
// Push data to existing array.
$arr['result'][] = $arrNewData;
You can add another array data to your existing array
Keep your existing data into a variable $data.
$data = [ ... ]; // here you have result index and array data
Then add new result item as an array.
$data['result'][] = [
'number' => 'AAA1225',
'short_description' => 'Cable replacement on workstation 12',
'state' => 'Closed'
];

how to remove base model name and its associated model name from find method in cakephp

I am retrieving data from the database with the help of belong to association using find method in cakephp. It's work perfectly but getting output like Array
(
[0] => Array
(
[PaymentLine] => Array
(
[Amount] => -1000.000
[OpenAmount] => -1000.000
[Narration] =>
)
[Payment] => Array
(
[TXNName] => Receipt-1
[TXNDate] => 2014-08-06
)
)
)
But I have to arrange data like Array
(
[0] => Array
(
[Amount] => -1000.000
[OpenAmount] => -1000.000
[Narration] =>
[TXNName] => Receipt-1
[TXNDate] => 2014-08-06
)
)
For these purpose I used Set::ClassicExtract method but that method not working for me... please help me...
Are you able to simply loop over the collection that is returned by the find method?
Perhaps try doing something like this:
$values = [];
foreach($array_of_arrays as $key => $array)
{
foreach($array as $value)
{
$values[] = $value;
}
}
$values will then contain all the values. The end result that you listed is not really possible to achieve if I understand what you are trying to do. This is because in that example you have duplicate keys for things such as 'id' and 'created'. If you only want to get the Arrays and store them in an array without the key then all you have to do is use:
array_values($array_of_arrays);
which will return the array but with the inner arrays having numeric keys instead of the enum ones.
If (for example) you had stored your data that you are getting back in a array called $dummy_data it would look something like this:
$dummy_data = [
'Profile' => Array
(
'id' => "12",
'user_id' => "121",
'skill' => "Baking Cakes",
'created' => "2007-05-01 10:31:01"
),
'User' => Array
(
'id' => "121",
'name' => "Gwoo the Kungwoo",
'created' => "2007-05-01 10:31:01"
)
];
If you know for a fact that the created values will always be the same for the 'Profile' and 'User' arrays then you can get a final array by using
array_merge($dummy_data['User'], $dummy_data['Profile']);

how to sort object array by key in php [duplicate]

This question already has answers here:
sorting arrays by months [duplicate]
(6 answers)
Closed 8 years ago.
I have an object array
<pre>stdClass Object
(
[October] => 13.88888888888889
[January] => 11.11111111111111
[April] => 17.77777777777778
[February] => 12.777777777777777
[August] => 17.77777777777778
[June] => 16.11111111111111
[May] => 16.11111111111111
[July] => 17.77777777777778
[November] => 12.222222222222221
[March] => 12.777777777777777
[December] => 11.11111111111111
[September] => 15.0
)
</pre>
I want to sort this array on the basis of month (key)
I used ksort() function but error coming that it must be array not object.
Then I converted it to array as array($data); and then used ksort() again but still no result.
Please help my guys how to do??
you should try the following code for your task:
$months=array("October" => "6.2","January" => "0.2","April" => "1.5","February" => "0.2","August" => "5.4","June" => "3.1","May" => "4.5","July" => "4.2","November" => "2.5", "March" => "0.5","December" => "0.7","September" => "6.9");
ksort($months);
foreach($months as $key=>$keyvalue)//$x=>$x_value
{
echo "<br>".$key."=>".$keyvalue;
}
You can use ksort() but you will first need to turn your object into an array.
You can do this with json_encode/json_decode
$array = json_decode( json_encode( $stdObject ), true );
ksort( $array );
foreach($array as $key => $val) {
echo $key. '=' .$val.'<br />'
}

Cakephp using Set class to fetch data with key starting at zero

I'm using Set class of Cakephp to format the find returned array but cannot seem to find a way to get the counter starting at zero and auto-increment for array keys so it is like
[0] => 3
[1] => 6
[2] => 12
I'm currently using below query to get the data from my HasAndBelongsToMany table.
$interest_ids = Set::combine($this->User->Interestsub->find('threaded', array
(
'conditions' => array
(
'Interestsub.name' => $interests
),
//'fields' => array('Interestsub.id'),
'recursive' => -1
)
),
'{n}.Interestsub.id',
'{n}.Interestsub.id'
);
The reason why I need this is that I'm currently trying to get the returned array as part of bigger parent array preparing to be saved for SaveAll function. To be formatted properly, I need below nested array coming out:
[0] => Array
(
[interestssub_id] => 12
[user_id] => 2
)
[1] => Array
(
[interestssub_id] => 22
[user_id] => 2
)
[2] => Array
(
[interestssub_id] => 32
[user_id] => 2
)
Is there a way we can use Combine class to format the returned array like above?
There's no real reason to use the Set class in this case. Just use good old fashioned php:
$threaded = $this->User->Interestsub->find('threaded', array(
'conditions' => array(
'Interestsub.name' => $interests
),
'recursive' => -1
));
$interest_ids = array();
foreach ($threaded as $thread) {
$interest_ids[] = array(
'interestssub_id' => $thread['Interestsub.id'],
'interestssub_id' => $thread['Interestsub.user_id']
);
}

Categories