Convert a json to multi-dimensional PHP array - php

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

Related

Convert large array of array to associative array without loop

I am using aws redis cache for quicker results instead of saving in db.
With this method
$result = $client->listTagsForResource([
'ResourceName' => '<string>', // REQUIRED
]);
Now it gives me result in given format.
Array
(
[0] => Array
(
[Key] => key1
[Value] => string1
)
[1] => Array
(
[Key] => status
[Value] => 1
)
)
I am unable to find a function in amazon docs which can give me direct results, so I decided to search in array , but finding in very large array with loops cost me in terms of time. So is there a way to convert it in following
Array
(
[key1] => string1,
[status] => 1
)
So I can directly access array index by using $array['key1']
You can try something like this to create new array:
$newArray = array_combine(
array_column($array, 'Key'),
array_column($array, 'Value')
);
echo $newArray['status'];

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

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!

retrieve specific key value from multidimensional array

I have the following array, since i converted the string i got back from a SOAP call to an array:
Array
(
[soapenvBody] => Array
(
[queryRequestsResponse] => Array
(
[result] => Array
(
[0] => Array
(
[BCRcustomId] => REQ16569
[BCRexternalId] => Array
(
)
[BCRrecordId] => a035700001CM60kAAD
[BCRrequestId] => a1J5700000857EYEAY
)
[1] => Array
(
[BCRcustomId] => SRQ100784
[BCRexternalId] => Array
(
)
[BCRrecordId] => a033E000001PxfAQAS
[BCRrequestId] => a1J3E0000000GSaUAM
)
)
)
)
)
I am trying to retrieve the BCRrecordId, since I need that item to make another SOAP call. I tried the following
function getID($array) {
return $array['BCRcustomId'];
}
//
$arr = array_map('getID', $array );
print_r($arr);
Now i get an error back on this saying it doesnt find it.
Undefined index: BCRcustomId in
index.php on line 97
[soapenvBody] => )Array (
My assumption is that it doenst go lower than 1 level in the array. Now i am not familair with these kinds of arrays, how would I solve this? By multiple for each loops? Or is there another way to retrieve these items
If $array is the whole response, you need to pass only result part of it:
$arr = array_map('getID', $array['soapenvBody']['queryRequestsResponse']['result']);

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']);

Merge or join two multidimensional arrays and copy keys/values over

How can I merge two different multidimensional arrays but copy the keys and values from the first array to the second array?
How I'm trying to get it to work is; the first array sets the input fields, which are then cloneable (cloning using jQuery, exactly like this: http://jsfiddle.net/8M98y/). Once you save field data, the second array is the resulting output. The problem is, the second array lacks the specific keys and values from the first array that are needed to output the saved data correctly.
Is there was a way to join or merge the arrays while copying the keys and values from the first array into the second array?
The first array that I need to copy the keys/values from looks like this:
Array
(
[group-1] => Array
(
[fields] => Array
(
[text-field-1] => Array
(
[name] => Text Field 1
[value] => Value 1
[comments] => true
)
[text-field-2] => Array
(
[name] => Text Field 2
[value] => Value 2
[comments] => false
)
)
)
)
The second array looks like this:
Array
(
[group-1] => Array
(
[fields] => Array
(
[text-field-1] => New value here
[text-field-2] => New value also
)
)
[group-2] => Array
(
[fields] => Array
(
[text-field-1] => Cloned group with new value
[text-field-2] => Cloned group with new value also
)
)
)
So if these two arrays were able to be merged, would need the output of the merged array to look like this: http://pastebin.com/uzuZs73B
I've tried using just array_merge( $array2, $array1 ), but the resulting output looks like this: http://pastebin.com/DucKGMN3 where they are in fact merged, but the keys and values aren't copied over.
EDIT: Should describe a use case here.
So how this works, the initial, unsaved output is two text inputs in a group which is created by the first array. The group is cloneable, using jQuery clone (this example here: http://jsfiddle.net/8M98y/). So if you add/clone one of more groups and then save, the resulting saved data would be the second array. The strings in the second array is the actual saved input values. Those would go into [value] in the first array.
However, the output of the fields is still based on the first array, meaning it can't output the cloned groups correctly as they're not an array and don't have the same keys and values from the first array.
If anyone can provide some insight on this, it would be hugely and greatly appreciated.
Sorry if I misunderstood the question, but is merging a requirement? If you have access to both arrays you could iterate over the second array, mapping the original key values, and overwriting with the new values as you go.
Your arrays:
$arr1 = Array
(
'group-1' => Array
(
'fields' => Array
(
'text-field-1' => Array
(
'name' => 'Text Field 1',
'value' => 'Value 1',
'comments' => 'true'
),
'text-field-2' => Array
(
'name' => 'Text Field 2',
'value' => 'Value 2',
'comments' => 'false'
)
)
)
);
$arr2 = Array
(
'group-1' => Array
(
'fields' => Array
(
'text-field-1' => 'New value here',
'text-field-2' => 'New value also'
)
),
'group-2' => Array
(
'fields' => Array
(
'text-field-1' => 'Cloned group with new value',
'text-field-2' => 'Cloned group with new value also'
)
)
);
Secret sauce:
foreach($arr2 as $k=>$v){
// Get the new values for this iteration
$val1 = $arr2[$k]['fields']['text-field-1'];
$val2 = $arr2[$k]['fields']['text-field-2'];
// Duplicate the original array
$arr2[$k]['fields'] = $arr1['group-1']['fields'];
// Insert the new values
$arr2[$k]['fields']['text-field-1']['value'] = $val1;
$arr2[$k]['fields']['text-field-2']['value'] = $val2;
}
echo '<pre>';
print_r($arr2);
echo '</pre>';
exit();
Which returns:
Array
(
[group-1] => Array
(
[fields] => Array
(
[text-field-1] => Array
(
[name] => Text Field 1
[value] => New value here
[comments] => true
)
[text-field-2] => Array
(
[name] => Text Field 2
[value] => New value also
[comments] => false
)
)
)
[group-2] => Array
(
[fields] => Array
(
[text-field-1] => Array
(
[name] => Text Field 1
[value] => Cloned group with new value
[comments] => true
)
[text-field-2] => Array
(
[name] => Text Field 2
[value] => Cloned group with new value also
[comments] => false
)
)
)
)

Categories