Illegal string offset in Fat Free Framework template - fat-free-framework

I fetch a result in Fat Free Framework with this:
$product = new DB\SQL\Mapper($db,'products');
$product->load(array('productId=:ID',':ID'=>$productId));
Then I walk through $product using the dry() method and do some calculations to some of it's fields. I want to make the re-calculated content of the $product available in my template, so I do:
$f3->set('product_contents', $product);
Now, when in my template I do:
<repeat group ="{{#product_contents}}" value="{{#item}}">
<p>{{#item.productName}}</p>
</repeat>
I get this error:
Internal Server Error
Illegal string offset 'productName'
I discovered that my {{#product_contents}} is a mapper object and not an array, hence the error.
The question is:
how can I still use the contents of $product in my template in repeat groups?

The cast() method is there to cast a mapper object to an array:
$f3->set('product_contents', $product->cast());

Just load the result into a variable
$output = $product->load(array('productId=:ID',':ID'=>$productId));
$f3->set('product_contents', $output);

Related

store string into array

In MySQL, I have a field name postcodes and the type is LONGTEXT. It stores several postcodes being separated by comma. How would I retrieve that and store it as an array for other use ?
you can use the PHP method explode().
one think you can't do, is to do a where x = x on it in the database.
In the model, you can set the mutator methods:
public function getPostcodesAttribute($value) {
return explode(',',$value);
}
public function setPostcodesAttribute($value) {
$this->attributes['postcodes'] = implode(',',$value);
}
Lets say that you have the result stored in a string like this:
$s = "6000,5447"; //$s = $array->postcodes;
you can get the each value on an index in an array using this:
$values= explode(",", $s);
echo $values[0]; // 6000
Or even better.. you can store it as json, and retrieve it as json in array format.
Store it as a JSON field in MySQL, Laravel encode and decode them when you retrieve and save them respectively
in your migration
$table->json('field_name');
then in the model
protected $json = ['field_name'];
then whenever you access the field, laravel will convert it to an array for you, you don't have to call any explicit methods.
Doc - https://laravel.com/docs/5.7/eloquent-mutators#attribute-casting
// the final array all the post codes are collected.
$postCodes = [];
foreach (Model::pluck('postcodes') as $stringCodes)
foreach (explode(',', $stringCodes) as $postCode) $postCodes[] = $postCode;

Laravel 5.4 formatting result set

Can someone help me convert this query so that my result set is in different format?
$sessions = new Session();
$results = $sessions->where('session_status', $status)->where('application_period_id', (int) ApplicationPeriod::all()->last()->id)->get()->pluck('speaker_id');
$speakers = Speaker::whereIn('id', $results)
->with('session.audiancesession.audiances')
->with('session.subjectsession.subjects')
->with(['session' =>
function ($query) use($status) {
$query->where('session_status', '=', $status);
}])->orderBy('last_name')->get();
This is requested via Ajax(axios)... Now this is how result is formatted:
Obj->data(array of objects)->[0]->name
->address
->session(array of objects)
->[0]->time
->fee
My issue is that my session parameter is array and there can only ever be (1) so I don't need to to be an array and I would like to have object (json) instead.
Thank you!
You might have more success if you change your client-side code to work with an array of sessions each session having its speaker, that means your original query would be like
$sessions = Sessions::with([
'speaker', 'audiancesession.audiances', 'subjectsession.subjects'
])->where('application_period_id', (int) ApplicationPeriod::orderBy('id','DESC')->first())->get();
Note the order by -> first in the ApplicationPeriod makes it so you don't have to get all application periods from the database to memory.
Then your client side should handle an array of sessions.
You can transform the above slightly using to get a similar result to what you need:
$speakers = $sessions->map(function ($session) {
$speaker = collect($session->speaker->toArray());
$speaker->put('session', collect($session->toArray())->except('speaker'));
return $speaker;
})->orderBy('last_name','DESC');
Though I wouldn't guarantee the result here as I've not tested it on your (complex looking) data.

How to convert params to array

I receive the following URL
/articles?difficulty=1,2
Inside the framework I want to receive an array from that - [1,2]. Is there any method in the framework to convert params like that into an array automatically? Can the framework do that? I can do like that explode(',', $params['difficulty']) - but I'm wondering whether this can be handled by the framework.
I don't want to pass params like that:
/articles?difficulty[]=1&difficulty[]=2
There is no helper in framework Request component for converting such values, it can be easily achieved with native PHP explode function. Use:
$array = explode(',', $string);
as you suggested.
But the wrapper of explode exists - \yii\helpers\StringHelper::explode(), it has additional options for trimming and skipping empty elements, you can use it too. But most of the times using regular explode should be enough.
try this
Use the Request class.
http://www.yiiframework.com/doc-2.0/yii-web-request.html
print_r(Yii::$app->request->get()); returns all get variables in an array. It's like doing print_r($_GET); in straight php.
If you want a specific $_GET variable you access it as follows:
Yii::$app->request->get('difficulty');
In your case it would be:
$success = Yii::$app->request->get('success');
$token = Yii::$app->request->get('token');
Then after that explode it with comma, so it will get converted into array.
$array = explode(',', $success );

Facebook JSON output

I have this code
$graph_url = "https://graph.facebook.com/100000070848126/statuses?access_token=".$params['access_token'];
$status = json_decode(file_get_contents($graph_url),true);
echo $status->data->message;
and I'm having a problem on how to output data in the array $status. I just don't know how to call the items for this feed
The second parameter of json_decode() is whether to create an associative array or not.
json_decode ( string $json [, bool $assoc = false])
You specified that you do want an array, so the way you would access the values would be like this -
echo $status['data']['message'];
If you leave out the true parameter of the json_decode() function, you'll be able to access the values in a more object oriented way like the syntax in your question.

CakePHP find on a json encoded field

I am creating a store in CakePHP and have added a text field which stores a json array of all the categories the store falls into.
How do I do a cake find on all stores that fall into the "gardening" category?
json encoded field:
["gardening","books-and-toys"]
I am thinking some sort of in_array() find but not quite sure.
Many Thanks
You can use the PHP method json_decode and return the JSON object as an associative array by setting the second option of that function to true. You can then call array_search for example to return the corresponding key.
<?php
$categories = json_decode($json, true);
$categoryKey = array_search('gardening', $categories);
$categoryName = $categories[$categoryKey];
?>
You can then use $categoryName in a CakePHP find() call.