I'm trying to create an array containing multiple objects.
I wrote this code (it's a member of an existing class)
public static $Roles = [
(object) ['code' => 'SO', 'name' => 'Socio'],
(object) ['code' => 'RESP', 'name' => 'Responsabile zona'],
(object) ['code' => 'AMM', 'name' => 'Amministratore'],
];
but I get this error:
syntax error, unexpected '(object)' (object) (T_OBJECT_CAST),
expecting ')'
on the second line.
I thought this should work, because I already used the same cast syntax to define associative array elements:
return view('edit-headquarter', [
'hq' => (object)['name' => '', 'id' => 0],
'submitAction' => 'insert'
]);
I'm doing something wrong?
EDIT: I'm using PHP 5.4.45
I'm not sure, but this can be related as suggested by Martin Persson
If you're using PHP version below v5.6, then you will not be allowed to have an expression as a default value for class members. Other than that, I don't see anything wrong with the way you have declared it.
To cast an associative array to object you can use a bit dirty, but widely used
$obj = json_decode(json_encode($arr));
Related
I've got simple array of objects:
"myObject" => [
'key1' => ["property1" => 'value1', "property2" => 'value2'],
'key2' => ["property1" => 'value1', "property2" => 'value2'],
...
],
When I'm returning this via laravel dot syntax:
return [
'listOfObjects' => trans(objects)
]
I've got:
myObject: {
key1: {property1:'value1', property2:'value2'},
key2: {property1:'value1', property2:'value2'},
etc..
}
It's simple.
Now how can I modify my return to get only an array of objects, without numbers:
myObject: {
{property1:'value1', property2:'value2'},
{property1:'value1', property2:'value2'},
etc..
}
Any ideas?
I don't think it is possible to solve in PHP. As it is said in the manual
"...index may be of type string or integer. When index is omitted, an
integer index is automatically generated, starting at 0..."
Also, what you are asking seems to be quite pointless. If you could describe what it is you are trying to accomplish, people might be able to help you better.
The function to use in this case is:
$tryit = trans('objects');
$new = collect($tryit)->flatten(1);
$new->values()->all();
unfortunatelly there is a bug in Laravel 5.6 on this function and it digs two level deep instead of one :/
[edit]
I think I now understand what you want. What you call an Array in PHP is not necessarily an Array in JSON. For JSON your "myObject" is an Object.
For JSON to recognize something as an Array, it can only have numbers as keys.
So change the keys from "key1", "key2", ... into 0, 1, ...
$result = [];
foreach($myObject as $element){
$result[] = $element;
}
return $result;
After that, $result looks like this
$result = [
0 => ["prop1" => "val1", "prop2" => "val2"],
1 => ["prop1" => "val1", "prop2" => "val2"]
]
Or equivalently in the short notation
$result = [
["prop1" => "val1", "prop2" => "val2"],
["prop1" => "val1", "prop2" => "val2"]
]
Now JSON should recognize this as an Array instead of an Object when Laravel converts $result to JSON or you make it yourself: return response()->json($result);
[previous:]
You can not return an object which has values but no keys.
The simplest form of keys are numbers, which is what arrays are using.
I am using Laravel 5.3.
existing Collection $a is
$a = collect(
[
0 =>[
'firstName' => 'John',
'lastName' => 'Doe'
],
1 =>[
'firstName' => 'Mary',
'lastName' => 'Jane'
]
]);
and desired result is as below:
$a = collect(
[
0 => [
'firstName' => 'John',
'lastName' => 'Doe',
'occupation' => 'engineer'
],
1 => [
'firstName' => 'Mary',
'lastName' => 'Jane',
'occupation' => 'accountant'
]
]);
I tried to test ->push(), ->put(), ->prepend() but no success. Please let me know the best way to do this.
You can use transform method which iterates over the collection and calls the given callback with each item in the collection. The items in the collection will be replaced by the values returned by the callback:
$a->transform(function ($item, $key) {
$item['occupation'] = 'some_value';
retrun $item;
});
Then check the value of $a:
dd($a);
Note that you have a collection of arrays, not a collection of collections. Hence, you can't use push(), put(), etc., in the sub-arrays.
The easiest way is probably just to treat it as an array:
$a[0]['occupation'] = 'engineer';
But you can also access at least the first element through the getter if you'd like:
$a->get(0)['occupation'] = 'engineer';
If you have an existing collection then you can get all the arrays from it using something like this:
$items = $existingCollection->all();
Now, you have an array of arrays in $items. So you can add key/value using something like this:
$item[0]['occupation'] = 'engineer';
$item[1]['occupation'] = 'accountant';
Now, you've modified the arrays so if you want to turn it back into a collection then you can do it easily using this:
$existingCollection = collect($items);
You could've also used map on the collection directly, for example:
$existingCollection->map(function ($person) {
$person['occupation'] = 'engineer';
return $person;
});
In this case, you can see that, all the person's occupation is going to be same but you can find out a way to make the difference but I can't give you more precise solution because I don't know much about your situation (You didn't share much).
I suddenly stuck here:
$source = (object) array(
'field_phone' => array(
'und' => array(
'0' => array(
'value' => '000-555-55-55',
),
),
),
);
dsm($source);
$source_field = "field_phone['und'][0]['value']";
dsm($source->{$source_field}); //This notation doesn't work
dsm($source->field_phone['und'][0]['value']); //This does
dsm() is Drupal developer function for debug printing variables, objects and arrays.
Why $source object doesn't understand $obj->{$variable} notation?
Notice: Undefined property: stdClass::$field_phone['und']['0']['value']
Because your object does not have a property that is named "field_phone['und'][0]['value']". It has a property that is named "field_phone" which is an array which has an index named "und" which is an array which has an index 0 and so on. But the notation $obj->{$var} does not parse and recursively resolve the name, as it shouldn't. It just looks for the property of the given name on the given object, nothing more. It's not like copy and pasting source code in place of $var there.
SOLVED:
getDimesions() ... google has made a type error.. LOL
facing some problems with array with colon in the name,
my $result is containing
gapiReportEntry::__set_state(array(
'metrics' =>
array (
'uniquePageviews' => 1523,
),
'dimensions' =>
array (
'pagePath' => '/',
'pageTitle' => 'Eventyrgolf',
'source' => 'google',
'medium' => 'organic',
'campaign' => '(not set)',
),
))
gapiReportEntry::__set_state(array(
'metrics' =>
array (
'uniquePageviews' => 210,
),
'dimensions' =>
array (
'pagePath' => '/dk/greenfee-og-banen-8/',
'pageTitle' => 'Greenfee og Banen',
'source' => 'google',
'medium' => 'organic',
'campaign' => '(not set)',
),
))
But some how i cannot get the "dimensions:private"... What to do?
I tried print_r():
$result->{"dimensions:private"}
$result['dimensions:private']
$result->dimensions
Full code:
$ga->requestReportData($profileId, $dimensions, $metrics, $sort, null, $fromDate, $toDate, 2, 30);
foreach ($ga->getResults() as $result) {
print_r($result->dimensions);
}
your $result is not an array, but an object. if you var_dump an object, you see it's contents, which in your case is an object with 2 private variables metrics and dimensions. To access these, the object probably has some accessors:
$result->getMetrics();
$result->getDimensions();
The dimensions property of $result object is private. That means it can be accessed only by objects of the same class.
Check if your gapiReportEntry class contains so called getter, that is a mathod which can access the property dimensions and return it's value to you. Look for something like getDimensions.
Read more about class field visibility here http://pl1.php.net/manual/en/language.oop5.visibility.php
EDIT
If your gapiReportEntry is a google analitics report, then this docs says that there is a getDimensions() method, so just call
$result->getDimensions();
EDIT #2
As suggested in comment, the class seems to have misspeled method name. The actual method is named getDim**es**ions:
$result->getDimesions();
Private is a reserved keyword in PHP and you should be scaping colon ":" with a backslash before it.
I am retrieving a DocumentSet in Lithium from MongoDB, but I don't want to process the documents all at once. Instead I would like to have a filter, which I just could tell something like this:
$manyDocuments->giveMeTheOneWhere(array('foo' => 'bar'));
I already tried to do it this way, but it didn't work:
$manyDocuments->find(function($singleDocument){
return ($singleDocument->foo == 'bar');
});
Even if I manually return true inside the closure, it always returns an empty DocumentSet.
Just to add clarity: I am not looking for a database-operation, instead I want to get one out of an already existent DocumentSet. Is there a fancy way to achieve this or do I need to iterate through the set using a custom function?
That looks right to me. Is that the exact code you are using?
For example, is the 'bar' value you are using something you are passing in?
I'm on the latest of the master branch of Lithium and wrote this unit test which works for me. I'm not really sure why you're getting an empty DocumentSet.
$docs = new DocumentSet(array('data' => array(
new Document(array('data' => array(
'id' => 1,
'foo' => 'bar'
))),
new Document(array('data' => array(
'id' => 2,
'foo' => 'baz'
))),
new Document(array('data' => array(
'id' => 3,
'foo' => 'bar'
))),
new Document(array('data' => array(
'id' => 4,
'blah' => 'ack'
)))
)));
$filtered = $docs->find(function($doc) {
return $doc->foo === 'bar';
});
$expected = array(
'0' => array('id' => 1, 'foo' => 'bar'),
'2' => array('id' => 3, 'foo' => 'bar')
);
$this->assertIdentical($expected, $filtered->data());
Instead of using find() I just used first() with a closure. This works as expected. Sadly that was the only thing I didn't try before. Excuse me for answering my own question.
Anyway I'd still be interested in a way to get another Document Set.