Issues trying to access an associative array converted from JSON in Laravel - json

I'm working on a Laravel project that implements react-jsonschema-form and I need to convert the values saved in the database to an associative array so I can pluck certain values from it. However I am getting strange results when doing so.
Here is the code I use to grab the JSON data from the table and then convert to an array:
$form = Form::where('id', $formId)->get();
$converted = json_decode($form[0]->form_data, true);
$formArray = print_r($converted, 1);
return $formArray;
For testing purposes I am simply rendering the data in the browser.
The result from the above return is:
Array
(
[1] => Array
(
[1.1] => New
[1.2] => Ms
[1.3] => Isobel Fleming
[1.4] => Array
(
[uprn] => 52375918
[address_1] => Fake Street
[address_2] =>
[address_3] =>
[town_city] => BRISTOL
[postcode] => BS1 3KE
)
[1.5] => 0129711011
[1.6] => 0800999111
[1.7] => 0781100022
[1.8] => isobelfleming#jourrapide.com
)
)
which is great. However when I try and access anything from it like:
return $formData[1][1.1]
I get:
String offset cast occurred
If I try using a string:
return $formData[1]['1.1']
I get:
Illegal string offset '1.1'
So I am not sure what to do to access this data. The problem is, although it's not ideal to have the associate keys with decimals in them, this is the way the schema is set up and it's several thousand lines long - this is just a snippet of the form data.
Is there anything that can be done in order to get the data from this array?

I figured it out. It seems like the following line was the problem:
print_r($converted, 1);
It didn't need to be printed as an array, I should have just used the $converted variable to access the data like so:
return $converted[1]['1.1'];

Related

Inserting JSON to DB Using Model in Laravel

I'm trying to use the model create option and this is my array:
$result = array(
'match_id' => $input['id'],
'score' => $input['score'],
'result' => $input['result'],
'headline' => NULL,
'article' => $input['report'],
'tries' => $input['try'],
'try_amount' => $input['tryquant'],
'conversions' => $input['conv'],
'conv_amount' => $input['convquant'],
'penalties' => $input['pens'],
'pen_amount' => $input['penquant'],
'dropgoals' => $input['dgs'],
'dg_amount' => $input['dgquant']
);
Result::create($result);
The contents of some of these are arrays themselves. eg:
$input['penquant'] = [
"4"
]
When I run my code, it saves the data to the DB simply as Array and throws up the following error:
ErrorException in helpers.php line 703: preg_replace(): Parameter mismatch, pattern is a string while replacement is an array
Can someone tell me what I'm doing wrong and how to fix it?
Shouldn't have rushed, forgot to use json_encode.
The best is to use mutators and accessors in your model.
example of mutator
// convert pen_amount from snake case to studly case
// The set...attribute (the ... is you field name which is in studly case) helps transform the data before you save it
// into the database
public function setPenAmountAttribute($value)
{
$this->attributes['pen_amount'] = serialize($value);
}
example of an accessor is
// convert pen_amount from snake case to studly case
// the get...Attribute (the ... is you field name which is in studly case) helps you convert the data back to it original state
public function getPenAmountAttribute($value)
{
return unserialize($value);
}
You can use accessors and mutators for all your fields that you want to save as array. This is elegant. No need to manually use json_encode and decode in your controllers.

Is there a name for storing data where each line either has a semi-colon or curly braces?

I am trying to understand how a Wordpress plugin works with data, when I pull it from MySQL it comes out like this:
a:1:{s:9:"home-team";a:6:{s:2:"id";s:9:"home-team";s:4:"slug";s:9:"home-team";s:4:"type";s:6:"select";s:4:"name";s:9:"Home Team";s:11:"description";s:0:"";s:4:"data";a:4:{s:7:"options";a:3:{s:60:"wpcf-fields-select-option-3892e2c3ad45e24dc7f47ff2ba880c33-2";a:2:{s:5:"title";s:13:"Chicago Bears";s:5:"value";s:1:"1";}s:60:"wpcf-fields-select-option-09fbd82bfa4142df6439c8e15d96dbfc-1";a:2:{s:5:"title";s:15:"New York Giants";s:5:"value";s:1:"2";}s:60:"wpcf-fields-select-option-7c7df972f933545b37c41ca249c686b4-1";a:2:{s:5:"title";s:15:"Oakland Raiders";s:5:"value";s:1:"3";}}s:8:"validate";a:1:{s:8:"required";a:3:{s:6:"active";s:1:"1";s:5:"value";s:4:"true";s:7:"message";s:22:"This Field is required";}}s:19:"conditional_display";a:2:{s:8:"relation";s:3:"AND";s:6:"custom";s:0:"";}s:16:"disabled_by_type";i:0;}}}
Is there a name for the way this is stored? To me it looks a little bit like JSON, but of course this is not JavaScript. Also, is there a way to clean it up easily (by using an online tool), so the first few lines would look like this:
a:1: {
s:9:"home-team";
a:6: {
s:2:"id";
s:9:"home-team";
s:4:"slug";
s:9:"home-team";
s:4:"type";
s:6:"select";
s:4:"name";
etc.. etc.. etc...
That's the PHP serialize format.
See : http://php.net/manual/en/function.serialize.php
Not sure how to get the formatted version exactly like you have it (but you could probably put that together easily), but here is another way to get an idea of what is in the serialized string:
$test_string= 'a:1:{s:9:"home-team";a:6:{s:2:"id";s:9:"home-team";s:4:"slug";s:9:"home-team";s:4:"type";s:6:"select";s:4:"name";s:9:"Home Team";s:11:"description";s:0:"";s:4:"data";a:4:{s:7:"options";a:3:{s:60:"wpcf-fields-select-option-3892e2c3ad45e24dc7f47ff2ba880c33-2";a:2:{s:5:"title";s:13:"Chicago Bears";s:5:"value";s:1:"1";}s:60:"wpcf-fields-select-option-09fbd82bfa4142df6439c8e15d96dbfc-1";a:2:{s:5:"title";s:15:"New York Giants";s:5:"value";s:1:"2";}s:60:"wpcf-fields-select-option-7c7df972f933545b37c41ca249c686b4-1";a:2:{s:5:"title";s:15:"Oakland Raiders";s:5:"value";s:1:"3";}}s:8:"validate";a:1:{s:8:"required";a:3:{s:6:"active";s:1:"1";s:5:"value";s:4:"true";s:7:"message";s:22:"This Field is required";}}s:19:"conditional_display";a:2:{s:8:"relation";s:3:"AND";s:6:"custom";s:0:"";}s:16:"disabled_by_type";i:0;}}}';
$unser = unserialize( $test_string);
print_r ( $unser );
Which will display:
Array
(
[home-team] => Array
(
[id] => home-team
[slug] => home-team
[type] => select
[name] => Home Team
[description] =>
[data] => Array
(
[options] => Array
(
[wpcf-fields-select-option-3892e2c3ad45e24dc7f47ff2ba880c33-2] => Array
(
[title] => Chicago Bears
[value] => 1
)
[wpcf-fields-select-option-09fbd82bfa4142df6439c8e15d96dbfc-1] => Array
(
[title] => New York Giants
[value] => 2
)
[wpcf-fields-select-option-7c7df972f933545b37c41ca249c686b4-1] => Array
(
[title] => Oakland Raiders
[value] => 3
)
)
[validate] => Array
(
[required] => Array
(
[active] => 1
[value] => true
[message] => This Field is required
)
)
[conditional_display] => Array
(
[relation] => AND
[custom] =>
)
[disabled_by_type] => 0
)
)
)
That's the way WordPress stores arrays and objects in the database. From the article WordPress serializes options and meta for you
In the most basic use case, serialization is a way to store arrays and objects directly in the database, which can only store numbers, text, and dates. Serialization takes an array and turns it into a serialized string. For example:
$data = array( 'apple', 'banana', 'orange' );
echo serialize( $data );
// Result is a string we can unserialize into an array:
// a:3:{i:0;s:5:"apple";i:1;s:6:"banana";i:2;s:6:"orange";}
WordPress has a few helper functions that we use instead of serialize() and unserialize() — maybe_serialize() and maybe_unserialize(). The first only serializes data that needs to be serialized — arrays and objects — and the second only unserializes data that is already serialized. (We have a lot of handy functions like these.)
You mention "when I pull it from MySQL it comes out like this", so you're probably not using the bundled functions to pull the data, like get_option(), get_post_meta() and get_user_meta(). Those functions take care of unserializing the data.
Worth noting that you should use a tool like WordPress (and others) Search and Replace Tool to search/replace inside the database. As it takes care of replacing strings inside serialized data.
You cannot simply change:
a:3:{i:0;s:5:"apple";i:1;s:6:"banana";i:2;s:6:"orange";}
to
a:3:{i:0;s:5:"grapefruit";i:1;s:6:"banana";i:2;s:6:"orange";}
Because it should be s:10:"grapefruit";, being 10 the number of characters in the string.

How in jquery (json) to call/name php array element

This is array in external php file
Array
(
[0] => Array
(
[CurrencyAbbreviation] => AUD
[CurrencyRate] => 0.50600000
[DateOfCurrencyRate] => 2013-07-11
[Units] => 1
)
)
Want to call for example CurrencyRate
Tried code like $('#currency_load').html(data.CurrencyRate); (Chrome F12 get 404 error).
For comparison. If php array is like this
$arr = array ('item1'=>"I love jquery4u",'item2'=>"You love jQuery4u",'item3'=>"We love jQuery4u");
and json $('#currency_load').html(data.item1);
then all works.
Do I need somehow to modify php array?

What is the best means to get the unique hash data into a JSON object without using an array when cycling through a DB Dataset?

I need to get the data into a JSON object but because I'm using the %data hash and it has the same address I'm getting the same data repeatedly in my JSON object.
This is the code that produces the JSON.
while (my ($orderID, $possessorName, $itemDescription, $...) = $sth->fetchrow_array)
{
%data = (orderID => $orderID, possessorName => $possessorName, itemDescription => $itemDescription,...);
$query_results{"job$index"} = {"data" => \%data};
$index++;
}
return $json_obj->pretty->encode(\%query_results, {ascii => 1, pretty => 1});
The problem is that the last item in my data set is masking all the previous items so I end up with one large JSON of the same exact data. I could use an array of hashes I suppose but this seems really messy and sloppy. How do I write the cleanest code to get my data? If an array of hashes is the best way to go please let me know and I'll do it. I all ready know how or can figure it out on my own.
What happens when you try:
my $index = 0;
my %query_results;
while (my ($orderID, $possessorName, $itemDescription, $...) = $sth->fetchrow_array) {
my %data = (orderID => $orderID, possessorName => $possessorName, itemDescription => $itemDescription,...);
$query_results{"job$index"}{'data'} = \%data;
$index++;
}
Previously, you used a %data hash declared in an outside scope; or worse, you didn't use strict; use warnings so %data was in fact an implicit global. Now, we declare the %data inside the loop which makes all the hashes distinct.
You could also copy the hash into a new hashref by {%data}.
That said, you don't even need that variable:
$query_results{"job$index"}{data} = {
# anonymous hashref here
orderID => $orderId,
possessorName => $possessorName,
itemDescription => ...
};

Extract data from array in DB (rails)

I am trying to extract some data from an array with the following syntax:
#entries_from_db = XrEntry.find(:all, :conditions => [:FeedURI => uri ], :select => 'json')
The :FeedURI is the record that contains an array with uri's ["123456", "23345", "4453"]
The uri is the variable wich contains the current uri.
The statement I'm trying to make is 'select JSON from XrEntry where FeedURI contains uri'
Im stuck on the part to access the array and always get several error msg's when I'm trying different code.
Does anyone has an idea?
Thanks!
I solved it with this syntax
#entries_from_db = XrEntry.find(:all, :conditions => ["FeedURI like ?", "%#{uri}%"] , :select => 'json')
the "%#{your_rails_variable}%" is needed to read in an array
You seem to have switched the condition syntax. you chould start with the db attribute and then the variable.
#entries_from_db = XrEntry.find(:all,
:conditions => { :uri => FeedURI },
:select => 'json')
That will return an array of XrEntry objects with only the json attribute present. To get an array of only the json data you could map it like this:
#json_array = #entries_from_db.map(&:json)