I am trying to access a collection and create a new object using part of the results.
I keep getting this Undefined offset: 0 and I can't seem to get around it.
Here is my foreach loop in my controller;
foreach($payments as $payment_key => $payment_value) {
//payment_value['Vendor ZIP'] will be something like "SW1A1AA"
$partial_vendor_zip = trim_and_convert($payment_value['Vendor ZIP'], 0, -3);
//$partial_vendor_zip will be something like "SW1A"
//SQL is something like SELECT * FROM postcode_coord WHERE postcode = 'SW1A' LIMIT 1;
$postcode_coord = PostcodeCoord::where('postcode', '=', $partial_vendor_zip)->take(1)->get();
print $postcode_coord['0']->lat; //causes error; Undefined offset: 0
$markers[] = (object)[
"postcode" => $postcode_coord->postcode,
"payment_name" => $payment_value['Contract Title'],
"full_postcode" => $payment_value['Vendor ZIP'],
"lat" => $postcode_coord->lat,
"lng" => $postcode_coord->lng,
];
}
Interestingly, I can still get a print of all the "lat"s - but I also get the error. If I replace that with just a print_r($postcode_coord); then here is a sample of my collection;
Illuminate\Database\Eloquent\Collection Object
(
[items:protected] => Array
(
[0] => App\Models\PostcodeCoord Object
(
[connection:protected] =>
[table:protected] =>
[primaryKey:protected] => id
[perPage:protected] => 15
[incrementing] => 1
[timestamps] => 1
[attributes:protected] => Array
(
[id] => 429
[postcode] => CF11
[lat] => 51.47
[lng] => -3.20
[created_at] => 2015-02-20 13:07:01
[updated_at] => 2015-02-20 13:07:01
)
[original:protected] => Array
(
[id] => 429
[postcode] => CF11
[lat] => 51.47
[lng] => -3.20
[created_at] => 2015-02-20 13:07:01
[updated_at] => 2015-02-20 13:07:01
)
[relations:protected] => Array
(
)
[hidden:protected] => Array
(
)
[visible:protected] => Array
(
)
[appends:protected] => Array
(
)
[fillable:protected] => Array
(
)
[guarded:protected] => Array
(
[0] => *
)
[dates:protected] => Array
(
)
[casts:protected] => Array
(
)
[touches:protected] => Array
(
)
[observables:protected] => Array
(
)
[with:protected] => Array
(
)
[morphClass:protected] =>
[exists] => 1
)
)
)
So that works! But I can't reference the attributes. Even when I try and change my query to something like;
$postcode_coord = PostcodeCoord::where('postcode', '=', $partial_vendor_zip)->take(1)->toArray();
And that just gives me an undefined method error.
Laravel is very confusing to me...
You need to do it like this:
$postcode_coord = PostcodeCoord::where('postcode', '=', $partial_vendor_zip)->first();
print $postcode_coord->lat;
$markers[] = (object)[
"postcode" => $postcode_coord->postcode,
"payment_name" => $payment_value['Contract Title'],
"full_postcode" => $payment_value['Vendor ZIP'],
"lat" => $postcode_coord->lat,
"lng" => $postcode_coord->lng,
];
Note the use of first() instead of take(1)->get(), since the latter will return a collection and the former will return a single item.
If you really want to use take(1)->get(), then you have to do it like this:
$postcode_coord = PostcodeCoord::where('postcode', '=', $partial_vendor_zip)->take(1)->get();
print $postcode_coord[0]->lat;
$markers[] = (object)[
"postcode" => $postcode_coord[0]->postcode,
"payment_name" => $payment_value['Contract Title'],
"full_postcode" => $payment_value['Vendor ZIP'],
"lat" => $postcode_coord[0]->lat,
"lng" => $postcode_coord[0]->lng,
];
Note here the use of 0 instead of '0' and that this index is also used in subsequent references to $postcode_coord.
Related
This is the Array I want to loop Into Events Index and get all the context print out of it how can i do this
Here is the Array Code Which i am trying to loop
[1] => stdClass Object
(
[id] => RPDNLNYO6U
[active] =>
[events] => Array
(
[0] => stdClass Object
(
[id] => RPDNLNYO6U_1
[created_at] => 2023-02-06T10:55:42.501003Z
[visibility] => all
[text] => Hi
[author_id] => 170bdd03-a163-49e9-4295-11fae376ff0e
)
[1] => stdClass Object
(
[id] => RPDNLNYO6U_2
[created_at] => 2023-02-06T10:55:44.102000Z
[visibility] => all
[text] => I need help
[author_id] => 170bdd03-a163-49e9-4295-11fae376ff0e
)
[2] => stdClass Object
(
[id] => RPDNLNYO6U_3
[created_at] => 2023-02-06T11:06:11.002000Z
[visibility] => agents
[type] => system_message
[text] => Chat is idle due to 10 minutes of inactivity
[system_message_type] => routing.idle
[text_vars] => stdClass Object
(
[duration] => 10
)
)
[3] => stdClass Object
(
[id] => RPDNLNYO6U_4
[created_at] => 2023-02-06T11:11:14.002000Z
[visibility] => all
[type] => system_message
[text] => Chat archived due to 15 minutes of inactivity
[system_message_type] => routing.archived_inactive
[text_vars] => stdClass Object
(
[duration] => 15
)
)
)
)
You can use a foreach loop in PHP to loop through the array and get all the context you need.
$array = [1 => (object) [
'id' => 'RPDNLNYO6U',
'active' => '',
'events' => [
(object) [
'id' => 'RPDNLNYO6U_1',
'created_at' => '2023-02-06T10:55:42.501003Z',
'visibility' => 'all',
'text' => 'Hi',
'author_id' => '170bdd03-a163-49e9-4295-11fae376ff0e'
]
]
]];
foreach ($array as $object) {
$id = $object->id;
$active = $object->active;
foreach ($object->events as $event) {
$event_id = $event->id;
$created_at = $event->created_at;
$visibility = $event->visibility;
$text = $event->text;
$author_id = $event->author_id;
echo "Event ID: $event_id, Created At: $created_at, Visibility: $visibility, Text: $text, Author ID: $author_id\n";
}
}
This will loop through the outer array and print out all the context for each event.
I have an application in Laravel that is taking a chunk of data from the dB and rendering it as JSON. The following line of code is generating the title error:
$decodedData['detail']['is_stem'] = isset($detailData->is_stem) ? $detailData->is_stem : 0;
The error is: Cannot use assign-op operators with string offsets
$decodedData is a larger array that is eventually returned as JSON. It is created thusly:
$decodedData = json_decode($detailData->detail, true);
$detailData is an object that looks like this:
App\CareersDetails Object
(
[connection:protected] => mysql
[table:protected] =>
[primaryKey:protected] => id
[keyType:protected] => int
[incrementing] => 1
[with:protected] => Array
(
)
[withCount:protected] => Array
(
)
[perPage:protected] => 15
[exists] => 1
[wasRecentlyCreated] =>
[attributes:protected] => Array
(
[id] => 4
[code] => 1234
[title] => StackOverFlow
[category] => My Category
[detail] => "Some details in JSON"
[is_stem] => 1
[created_at] => 2018-12-28 17:05:15
[updated_at] => 2018-12-28 17:05:15
)
[original:protected] => Array
(
[id] => 7
[code] => 7890
[title] => StackOverFlowRocks
[category] => My Category
[detail] => "Some details in JSON format"
[is_stem] => 1
[created_at] => 2018-12-28 17:05:15
[updated_at] => 2018-12-28 17:05:15
)
[changes:protected] => Array
(
)
[casts:protected] => Array
(
)
[dates:protected] => Array
(
)
[dateFormat:protected] =>
[appends:protected] => Array
(
)
[dispatchesEvents:protected] => Array
(
)
[observables:protected] => Array
(
)
[relations:protected] => Array
(
)
[touches:protected] => Array
(
)
[timestamps] => 1
[hidden:protected] => Array
(
)
[visible:protected] => Array
(
)
[fillable:protected] => Array
(
)
[guarded:protected] => Array
(
[0] => *
)
)
When I debug using:
print_r($detailData->is_stem);
The system outputs a 1. Hence it is set.
Alternatively, is my $decodedData array at fault?
Update
Thanks to the comments, I noticed my $decodedData is not an array, it is a string.
Hence I dumped
`$detailData->detail`
To my browser page with print_r and ran it via a simple, seperate PHP script:
$payload = "JSON FROM $detailData->detail";
$data = json_decode($payload,true);
$data['detail']['is_stem'] = 1;
print_r($data );
This works. Hence my question is now why does the string dump from print_r work and my Laravel based-app doesn't?
Or, in other words, why is json_decode returning a string in the Laravel App but an Array in the PHP app with the same input?
The issue in my instance was my JSON data was double encoded. The fix was:
$decodedData = json_decode(json_decode($detailData->detail), true);
Note, this is not best practice and is a complete oversight on our part so we will be changing this ASAP.
Cleeng_Entity_Collection Object
(
[entityType:protected] => Cleeng_Entity_SubscriptionOffer
[items:protected] => Array
(
[0] => Cleeng_Entity_SubscriptionOffer Object
(
[id:protected] => S955494970_US
[publisherEmail:protected] => vidya+mtc#ooyala.com
[url:protected] =>
[title:protected] => Annual subscription
[description:protected] =>
[period:protected] => year
[price:protected] => 49.99
[applicableTaxRate:protected] => 0
[currency:protected] => USD
[accessToTags:protected] => Array
(
[0] => d962607d3d4c4e3c98a343c7bcb64027
)
[active:protected] => 1
[createdAt:protected] => 1473681112
[updatedAt:protected] => 1473858745
[geoRestrictionEnabled:protected] =>
[geoRestrictionType:protected] =>
[geoRestrictionCountries:protected] => Array
(
)
[pending:protected] =>
[country] => US
[socialCommissionRate] => 0
[averageRating] => 4
[contentType] =>
[freePeriods] => 0
[freeDays] => 0
[expiresAt] =>
)
)
[totalItemCount:protected] => 5
[pending:protected] =>
)
All you need to do is just convert the Collection to a Regular Array and then json_encode() the Result like so:
<?php
$entityCollection = "???"; // THIS IS THE DATA FROM Cleeng_Entity_Collection Object
$entityArray = $entityCollection->toArray();
$entityJSON = json_encode($entityArray);
I am working with Laravel 5.2. I want to write a query in two parts like this:
$getData = DB::table($table)
->where($where);
$getData->first();
return $getData;
But it is not working for me. It Not provides correct data to me.
It gives:
Array ( [aggregate] => [columns] => [distinct] => [from] => countries [joins] => [wheres] => Array ( [0] => Array ( [type] => Nested [query] => Array ( [aggregate] => [columns] => [distinct] => [from] => countries [joins] => [wheres] => Array ( [0] => Array ( [type] => Basic [column] => country_name [operator] => = [value] => India [boolean] => and ) ) [groups] => [havings] => [orders] => [limit] => [offset] => [unions] => [unionLimit] => [unionOffset] => [unionOrders] => [lock] => ) [boolean] => and ) ) [groups] => [havings] => [orders] => [limit] => 1 [offset] => [unions] => [unionLimit] => [unionOffset] => [unionOrders] => [lock] => )
But it works correctly when i call like this:
$getData = DB::table($table)
->where($where)->first();
return $getData;
Can we not call a query in two parts in laravel.
You have to get back the returned data from $getData->first();
$getData = DB::table($table)
->where($where);
$getData = $getData->first(); // <----
return $getData;
Hi I am using php with cassandra database. I am trying to get username and password from cassandra database. It return the below result.
Cassandra\Rows Object(
[columns:protected] => Array
(
[0] => Cassandra\ColumnSpec Object
(
[keyspace:protected] => team1_groupboxx
[tablename:protected] => gb_adminusers
[name:protected] => au_username
[type:protected] => Cassandra\TypeSpec Object
(
[type:protected] => 13
[customTypename:protected] =>
[keyType:protected] =>
[valueType:protected] =>
)
)
[1] => Cassandra\ColumnSpec Object
(
[keyspace:protected] => team1_groupboxx
[tablename:protected] => gb_adminusers
[name:protected] => au_password
[type:protected] => Cassandra\TypeSpec Object
(
[type:protected] => 13
[customTypename:protected] =>
[keyType:protected] =>
[valueType:protected] =>
)
)
)
[rowCount:protected] => 1
[columnCount:protected] => 2
[current:protected] => 0
[rows:protected] => Array
(
[0] => Array
(
[0] => k2badmin
[1] => f2c452187d4af19966187e15f1e944e1
)
)
)
But I want to get the query result in below format.
Array (
[au_username] => admin
[au_password] => f2c452187d4af19966187e15f1e944er
)
where au_username and au_password are the column names of my table.