DBIx might_have with custom conditions, object always undef - dbix-class

Update I normally roam in the latex part of stachexchange and thus we have to provide a full minimal example to reproduce issues.
So here is a full breakdown. The original description of my problem is found below.
Test DB setup, we using SQLite, create.sql:
PRAGMA foreign_keys = ON;
DROP TABLE IF EXISTS `member`;
DROP TABLE IF EXISTS `address`;
create table `member` (
`uid` VARCHAR(30) NOT NULL,
`name` VARCHAR(255) DEFAULT '',
CONSTRAINT `pk_uid` PRIMARY KEY(`uid`)
);
INSERT INTO `member` VALUES ('m1','Test 1'),('m2','Test 2');
create table `address` (
`uid` VARCHAR(30) NOT NULL,
`address_type` VARCHAR(30) NOT NULL, -- will either be work or home
`text` TEXT DEFAULT '',
CONSTRAINT `pk_uid_type` UNIQUE(`uid`,`address_type`)
CONSTRAINT `fk_uid`
FOREIGN KEY(uid)
REFERENCES member(uid)
ON DELETE CASCADE
);
INSERT INTO `address` VALUES
('m1','home','home address'),
('m1','work','work address'),
('m2','home','home address');
to be loaded into test.db via
sqlite3 test.db < create.sql
As we can see from the test data m1 has two entries in address whereas m2 has one.
Next the DBIx setup (I have no idea how to merge this into a single file, ideas a welcome as it would making the test easier). These are autogenerated via dbicdump, here I've removed alle the comments.
Schema.pm:
use utf8;
package Schema;
use strict;
use warnings;
use base 'DBIx::Class::Schema';
__PACKAGE__->load_namespaces;
1;
Schema/Result/Member.pm:
use utf8;
package Schema::Result::Member;
use strict;
use warnings;
use base 'DBIx::Class::Core';
__PACKAGE__->table("member");
__PACKAGE__->add_columns(
"uid",
{ data_type => "varchar", is_nullable => 0, size => 30 },
"name",
{ data_type => "varchar", default_value => "", is_nullable => 1, size => 255 },
);
__PACKAGE__->set_primary_key("uid");
__PACKAGE__->has_many(
"addresses",
"Schema::Result::Address",
{ "foreign.uid" => "self.uid" },
{ cascade_copy => 0, cascade_delete => 0 },
);
# I added
__PACKAGE__->might_have(
"home_address" => "Schema::Result::Address",
#{ 'foreign.uid' => 'self.uid'},
sub {
my $args = shift;
return {
"$args->{foreign_alias}.uid" => "$args->{self_alias}.uid",
"$args->{foreign_alias}.address_type" => 'home',
}
},
{ cascade_copy => 0, cascade_delete => 0 },
);
__PACKAGE__->might_have(
"home_address_alt" => "Schema::Result::Address",
{ 'foreign.uid' => 'self.uid'},
{ cascade_copy => 0, cascade_delete => 0 },
);
__PACKAGE__->might_have(
"work_address" => "Schema::Result::Address",
sub {
my $args = shift;
return {
"$args->{foreign_alias}.uid" => "$args->{self_alias}.uid",
"$args->{foreign_alias}.address_type" => 'work',
}
},
{ cascade_copy => 0, cascade_delete => 0 },
);
1;
Schema/Result/Address.pm:
use utf8;
package Schema::Result::Address;
use strict;
use warnings;
use base 'DBIx::Class::Core';
__PACKAGE__->table("address");
__PACKAGE__->add_columns(
"uid",
{ data_type => "varchar", is_foreign_key => 1, is_nullable => 0, size => 30 },
"address_type",
{ data_type => "varchar", is_nullable => 0, size => 30 },
"text",
{ data_type => "text", default_value => "", is_nullable => 1 },
);
__PACKAGE__->add_unique_constraint("uid_address_type_unique", ["uid", "address_type"]);
__PACKAGE__->belongs_to(
"u",
"Schema::Result::Member",
{ uid => "uid" },
{ is_deferrable => 0, on_delete => "CASCADE", on_update => "NO ACTION" },
);
1;
My test script:
#!/usr/bin/perl
use strict;
use warnings;
use utf8;
use open qw/:std :utf8/;
use Data::Dumper;
$Data::Dumper::Sortkeys = 1;
$Data::Dumper::Maxdepth = 0;
use Modern::Perl;
use lib qw(.);
use Schema;
BEGIN {
$ENV{DBIC_TRACE} = 1;
}
my $schema = Schema->connect(
'dbi:SQLite:dbname=test.db',
'',
'',
{
on_connect_do => 'PRAGMA foreign_keys = ON',
sqlite_unicode => 1,
RaiseError => 1,
}
);
my $row = $schema->resultset('Member')->find({ uid => 'm1'},
{
prefetch => ['home_address','work_address'],
}
);
# these are both undef
print Dumper $row->home_address;
print Dumper $row->work_address;
# using
$row = $schema->resultset('Member')->find({ uid => 'm1'},
{
prefetch => ['home_address','work_address'],
result_class => 'DBIx::Class::ResultClass::HashRefInflator',
}
);
# then
print Dumper $row;
# gives
# $VAR1 = {
# 'home_address' => undef,
# 'name' => 'Test 1',
# 'uid' => 'm1',
# 'work_address' => undef
# };
# using the "normal might_have home_address_alt in Member on m2
$row = $schema->resultset('Member')->find({ uid => 'm2'},
{
prefetch => ['home_address_alt'],
result_class => 'DBIx::Class::ResultClass::HashRefInflator',
}
);
say Dumper $row;
# does work, but only because m2 only have a single entry in Address whereas m1 has two
$row = $schema->resultset('Member')->find({ uid => 'm1'},
{
prefetch => ['home_address_alt'],
result_class => 'DBIx::Class::ResultClass::HashRefInflator',
}
);
say Dumper $row;
# which gives this warning: DBIx::Class::Storage::DBI::select_single(): Query returned more than one row. SQL that returns multiple rows is DEPRECATED for ->find and ->single and returns the first found.
The DBIC_TRACE gives
SELECT me.uid, me.name, home_address.uid, home_address.address_type, home_address.text, work_address.uid, work_address.address_type, work_address.text FROM member me LEFT JOIN address home_address ON ( home_address.address_type = ? AND home_address.uid = ? ) LEFT JOIN address work_address ON ( work_address.address_type = ? AND work_address.uid = ? ) WHERE ( me.uid = ? ): 'home', 'me.uid', 'work', 'me.uid', 'm1'
Which if you run it manually against test.db gives
m1|Test 1|m1|home|home address|m1|work|work address
So the SQL is capable of producing the correct output. But the accessors/objects whatever you want to call them, keeps being empty. I'd like to know why?
My original question:
I my data I have members and they can each have up to two addresses (home and work) both stored in the same table
So I have something similar to
Member; primary key(uid)
Address; unique(uid,address_type) # the latter is work or home
when I grab a member I'd like to prefetch the up to two addresses using might_have relationships. So in Schema::Result::Member I have
__PACKAGE__->might_have(
"home_address" => "Schema::Result::Address",
sub {
my $args = shift;
return {
"$args->{foreign_alias}.uid" => "$args->{self_alias}.uid",
"$args->{foreign_alias}.address_type" => 'home',
}
},
{ cascade_copy => 0, cascade_delete => 0 },
);
__PACKAGE__->might_have(
"work_address" => "Schema::Result::Address",
sub {
my $args = shift;
return {
"$args->{foreign_alias}.uid" => "$args->{self_alias}.uid",
"$args->{foreign_alias}.address_type" => 'work',
}
},
{ cascade_copy => 0, cascade_delete => 0 },
);
And I call it via
my $row = $self->schema->resultset('Member')
->find({uid => $uid},
{
prefetch => [qw/home_address work_address/],
});
As far as I can see from DBIC_TRACE the generated SQL is correct
... LEFT JOIN address home_address ON ( home_address.address_type = ? AND home_address.uid = ? ) LEFT JOIN address work_address ON ( work_address.address_type = ? AND work_address.uid = ? ) WHERE ( me.uid = ? ): 'home', 'me.uid', 'work', 'me.uid', '120969'
but $row->home_address is always just undef and I do not understand why.
I have also tried
__PACKAGE__->might_have(
"home_address" => "Schema::Result::Address",
{ 'foreign.uid' => 'self.uid' },
{ where => { 'address_type' => 'home' } , cascade_copy => 0, cascade_delete => 0 },
);
__PACKAGE__->might_have(
"work_address" => "Schema::Result::Address",
{ 'foreign.uid' => 'self.uid' },
{ where => { 'address_type' => 'work' } , cascade_copy => 0, cascade_delete => 0 },
);
but the where part is never a part of the DBIC_TRACE.
Any ideas as to what I'm missing here?

The DBIx::Class docs have an example of a custom relationship with fixed values on the remote side of the rel: https://metacpan.org/pod/DBIx::Class::Relationship::Base#Custom-join-conditions.
The part you've missed is the -ident, so DBIC can distinguish between a fixed value and a related column.
Because of that the query ends up with a bind variable that is passed the literal string 'me.uid' on execution.

Related

Perl nested hashes matching and merging

I have a file that is read and split into %ojects, the %objects are populated as shown below.
$VAR1 = 'cars';
$VAR2 = {
'car1' => {
'info1' => '"fast"',
'info2' => 'boring'
},
'car2' => {
'info1' => '"slow"',
'info2' => 'boring info'
},
'car3' => {
'info1' => '"unique"',
'info2' => 'useless info'
}
};
$VAR3 = 'age';
$VAR4 = {
'new' => {
'info3' => 'rust',
'info4' => '"car1"'
},
'old' => {
'info3' => 'shiny',
'info4' => '"car2" "car3"'
}
}
};
My goal is to insert data like "car1 fast rust, car2 slow shiny, car3 unique shiny" in a DB but I can't get e.g. "rust to match based on info4 in age" ..
my $key = cars;
my $key2 = age;
foreach my $obj (keys %{$objects{$key}}) { # for every car
#info1s = $objects{$type}{$obj}{'info1'} =~ m/"(.*?)"/g; # added to clean up all info1
foreach my $infos ($info1s) {
dbh execute insert $obj $infos # this gives me "car1 fast, car2 slow, car3 unique"
}
...
Can somebody please point me in the right direction to fetch and store info4 with related info1/info2?
Thanks!
I take the objective to be as follows.
Get values for (info4) keys in $VAR4, at the deepest-level hashref, and find them as top-level keys in $VAR2 hashref. Then associate with them both a value from a (info3) key, their "sibling" in their own $VAR4's deepest level hashref, as well as the value of a key (info1) from $VAR2.
One can traverse the structure by hand for this purpose, specially if it's always with the same two levels as shown, but it's easier and better with libraries. I use Data::Leaf::Walker to get leaves (deepest values) and key-paths to them, and Data::Diver to get values for known paths.
use warnings;
use strict;
use feature 'say';
use Data::Dump;
use Data::Leaf::Walker;
use Data::Diver qw(Dive);
my $hr1 = {
'car1' => { 'info1' => 'fast', 'info2' => 'boring' },
'car2' => { 'info1' => 'slow', 'info2' => 'boring info' },
'car3' => { 'info1' => 'unique', 'info2' => 'useless info' }
};
my $hr2 = {
'new' => { 'info3' => 'rust', 'info4' => 'car1' },
'old' => { 'info3' => 'shiny', 'info4' => 'car2 car3' }
};
my $walker = Data::Leaf::Walker->new($hr2);
my %res;
while ( my ($path, $value) = $walker->each ) {
next if $path->[-1] ne 'info4';
# Some "values" have multiple needed values separated by space
for my $val (split ' ', $value) {
# Get from 'info4' path the one to its sibling, 'info3'
my #sibling_path = ( #{$path}[0..$#$path-1], 'info3' );
# Collect results: values of `info3` and `info1`
push #{$res{$val}},
Dive( $hr2, #sibling_path ),
Dive( $hr1, ($val, 'info1') );
}
}
dd \%res;
This assumes a few things and takes some shortcuts, for simplicity.
For one, I use explicit infoN keys from the questions, and the two-level structure. If data is, or can be different, this shouldn't be hard to adjust.
Next, this assumes that a value like car1 always exists as a key in the other hashref. Add an exists check for that key if it is possible that it doesn't exist as a key.
I've removed some extra quotes from data. (If that's for database entry do that when constructing the statement. If data comes in with such extra quotes it should be easy to adjust the code to take them into account.)
The above program prints
{
car1 => ["rust", "fast"],
car2 => ["shiny", "slow"],
car3 => ["shiny", "unique"],
}
(I use Data::Dump to display complex data structure, for its simplicity and default compact output.)

How to pass multi-dimensional arrays through url as query parameters? and access these parameters in laravel 6.0

I am trying to pass a multi-dimensional array as a query parameter in the below URL:
{{serverURL}}/api/v1/classes?with[]=section.courseteacher&addl_slug_params[0][0]=test&addl_slug_params[0][1]=test1&addl_slug_params[0][2]=test0
what is wrong with the above URL?
My code to access these parameters in Laravel 6.0 is below:
$addl_slug_params = $request->query('addl_slug_params');
$i=0;
foreach ($addl_slug_params as $s) {
$j=0;
foreach($s as $asp) {
print_r('addl_slug_params : ('.$i.':'.$j.') : '.$asp); die();
$j=$j+1;
}
$i = $i+1;
}
Result:
addl_slug_params : (0:0) : test
Problem: test1 and test0 are not accessible..
What should I do?
The problem is the die(); after printr(), the loop will run once, aka only addl_slug_params : (0:0) : test
To help you visualize it better, I added an extra break after each loop:
foreach ($addl_slug_params as $s) {
$j=0;
foreach($s as $asp) {
echo('addl_slug_params : ('.$i.':'.$j.') : '.$asp);
echo nl2br(PHP_EOL);
$j=$j+1;
}
$i = $i+1;
}
Will result in the following:
addl_slug_params : (0:0) : test
addl_slug_params : (0:1) : test1
addl_slug_params : (0:2) : test0
here is a solution for multi-dimensional arrays. Developed in 2~ hours, definitely needs improvement but hopefully helps you out :)
Route::get('example', function (\Illuminate\Http\Request $request) {
$addl_slug_params = [
[
1 => [
'title' => 'Test 1',
'slug' => 'test1'
],
2 => [
'title' => 'Test 2',
'slug' => 'test2'
],
3 => [
'title' => 'Test 3',
'slug' => 'test3'
],
],
];
// Encode
$prepend = 'addl_slug_params';
$query = "?$prepend";
$tempSlugs = $addl_slug_params[0];
$lastIndex = count($tempSlugs);
foreach ($addl_slug_params as $pIndex => $params) {
foreach ($params as $sIndex => $slugData) {
$tempQuery = [];
foreach ($slugData as $sdIndex => $data) {
// Replace '-' or ' -' with ''
$encodedString = preg_replace('#[ -]+#', '-', $data);
// title = test1
$tempString = "$sdIndex=$encodedString";
$tempQuery[] = $tempString;
}
$dataQuery = implode(',', $tempQuery);
$appendStr = ($sIndex !== $lastIndex) ? "&$prepend" : '';
// Set the multidimensional structure here
$query .= "[$pIndex][$sIndex]=[$dataQuery]$appendStr";
}
}
// DECODE
// ?addl_slug_params[0][1]=[title=Test-1,slug=test1]&addl_slug_params[0][2]=[title=Test-2,slug=test2]&addl_slug_params[0][3]=[title=Test-3,slug=test3]
$slugParams = $request->query('addl_slug_params');
$slugParamData = [];
foreach ($slugParams as $slugItems) {
foreach ($slugItems as $slugItem) {
// Replace [title=test,slug=test1] into 'title=test,slug=test1' and explode
// into into an array, and split title=test into [title => test]
$splitArray = explode(',', (str_replace(array('[', ']'), '', $slugItem)));
$slugItemData = [];
foreach ($splitArray as $value) {
$data = explode('=', $value);
$slugItemData[$data[0]] = $data[1];
}
$slugParamData[] = $slugItemData;
}
}
dd($slugParamData);
});
I have solved the problem using associative arrays as it gives more flexibility and Garrett's solution definitely helped
new url: {{serverURL}}/api/v1/classes?with[]=section.courseteacher&addl[users][params]=name
laravel code:
`
foreach ($addl_data_array as $addl_slug => $addl_slug_data) {
foreach ($addl_slug_data as $key => $value) {
$params = null;
$where_raw = null;
$where_has = null;
$with_relationships = null;
$with_timestamps = null;
}
}
`

Why assigning list containing array to array itself causes recursion in perl?

I'm using DBIX::Class and generating conditions for search like that:
my #array;
push #array, { condition1 => 'value1' };
push #array, [ { condition2 => 'value2' }, { condition3 => 'value3' } ];
All this conditions must be checked using AND operator, that's why I wrote this:
#array = ( -and => #array );
After running code with such conditions process on my virtual machine started to use up to 8 Gb memory. I thought that it was recursion problems and I didn't mistake. I checked logs and saw records about deep recursion but I couldn't find anything about my case in internet.
Is there problems with assigning list containing array to array itself?
Or maybe it is a problem with DBIX::Class (SQL::Abstract)? Why it causes deep recursion?
Update. This is the real code from project:
sub faq {
my ( $self ) = #_;
my #cond;
if ( $self->param('faq_type') ) {
push #cond,
{
'me.faq_type' => $self->param('faq_type'),
};
}
if ( my $search = $self->param('search') ) {
push #cond,
[
'me.title' => { ilike => "%$search%" },
'me.text' => { ilike => "%$search%" },
];
}
#cond = ( -and => #cond );
my %attr = (
join => 'page_category',
rows => $self->param('limit'),
offset => $self->param('offset'),
order_by => { -desc => 'id' },
result_class => 'BUX::Util::HashRefInflator',
'+select' => [ qw( page_category.name ) ],
'+as' => [ qw( category_name ) ],
);
my #pages = BUX::DB->rs('Page')->search( \#cond, \%attr )->all;
my $total_count = BUX::DB->rs('Page')->count( \#cond );
return $self->render(json => {
pages => \#pages,
count => $total_count
});
}
And log records:
Deep recursion on subroutine "SQL::Abstract::_SWITCH_refkind" at /opt/perlbrew/perls/perl-5.14.4/lib/site_perl/5.14.4/SQL/Abstract.pm line 719.
Deep recursion on subroutine "SQL::Abstract::_recurse_where" at /opt/perlbrew/perls/perl-5.14.4/lib/site_perl/5.14.4/SQL/Abstract.pm line 546.
Deep recursion on subroutine "SQL::Abstract::_where_ARRAYREF" at /opt/perlbrew/perls/perl-5.14.4/lib/site_perl/5.14.4/SQL/Abstract.pm line 687.
Deep recursion on subroutine "SQL::Abstract::_where_HASHREF" at /opt/perlbrew/perls/perl-5.14.4/lib/site_perl/5.14.4/SQL/Abstract.pm line 493.
Deep recursion on subroutine "SQL::Abstract::_where_unary_op" at /opt/perlbrew/perls/perl-5.14.4/lib/site_perl/5.14.4/SQL/Abstract.pm line 596.
Deep recursion on subroutine "SQL::Abstract::_where_op_ANDOR" at /opt/perlbrew/perls/perl-5.14.4/lib/site_perl/5.14.4/SQL/Abstract.pm line 645.
P.S. BUX::DB is the subclass of DBIx::Class and rs is a shortcut for resultset.
When specifying several conditions that should all be met to search
with DBIx::Class, the usual way to do this is by passing a hashref
with the column names as keys and the conditions as values.
While it is possible to instead specify an arrayref of hashrefs with the '-and' keyword, this is most often unnecessary - especially if you only have one condition to specify!
NOTE: I am not certain { -and => #cond } does what you want, have you tried replacing it with { -and => \#cond } ( Note the arrayref) ? This could be the reason why SQL::Abstract gets confused, though I'm unsure how that would end up being a recursion.
SECOND NOTE: I find #cond = ( -and => \#cond ) confusing and it may cause trouble. I would suggest working with a hashref passed into search, as it should be called with, and setting the -and key instead, by adapting my first example.
This is how I would specify the conditions:
my $cond;
if ( my $faq_type = $self->param('faq_type') ){
$cond->{'me.faq_type'} = $faq_type;
}
if ( my $search = $self->param('search') ){
$cond->{-or} = [
{ $cond->{'me.title'} = { ilike => '%$search%' }, },
{ $cond->{'me.text' } = { ilike => '%$search%' }, },
];
}
An alternative to consider, would be to first specify the 'faq_type' search and store the resulting rs, to then refine it further as necessary, this seems more in line with the spirit of DBIx::Class to me:
my $pages_rs = BUX::DB->rs('Page');
if ( my $faq_type = $self->param('faq_type') ){
$pages_rs = $pages_rs->search({ 'me.faq_type' => $faq_type });
}
if ( my $search = $self->param('search') ){
$pages_rs = $pages_rs->search({
-or => [
'me.title' => { ilike => "%$search%" },
'me.text' => { ilike => "%$search%" },
];
});
}
my %attr = (
join => 'page_category',
rows => $self->param('limit'),
offset => $self->param('offset'),
order_by => { -desc => 'id' },
result_class => 'BUX::Util::HashRefInflator',
'+select' => [ qw( page_category.name ) ],
'+as' => [ qw( category_name ) ],
);
$pages_rs = $pages_rs->search( undef, \%attr );
my #pages = $pages_rs->all; # This executes the query
Please keep in mind this is untested as I currently don't have an easy way of verifying this. If this does not help, feel free to comment and I'll try and fix whatever may be off.
EDIT: to not leave something in that is wrong, I've removed the (irrelevant) page count I put in.

Strange behaviour of Perl's push function

I am writing a dedicated ICS (iCalendar file) parser.
I pass an array to a subroutine. All variables are single values apart from $notdates which is a comma-separated list of dates.
#entryl = ($dtstart, $dtend, $attendee, $lastmod, $uid, $notdates);
&entrytoarray(#entryl);
sub entrytoarray {
# print Dumper #_;
my $shiftdur = (&stamptoepoc($_[1]) - &stamptoepoc($_[0])) / 60 / 60;
my $attendee = $_[2];
my $deleted = $_[5];
$attendee =~ /ATTENDEE;USER-KEY=([^;]*);CN=([^;]*);.*:(.*)/;
my %ehash = (
"STARTDATE" , &stamptodate($_[0]),
"ENDDATE" , &stamptodate($_[1]),
"STARTSTAMP" , $_[0],
"ENDSTAMP" , $_[1],
"USERKEY" , $1,
"CN" , $2,
"EMAIL" , $3,
"LASTMOD" , $_[3],
"UID" , $_[4],
"DURATION" , $shiftdur
);
# Only keep current data
my $fdays = 4;
my $tdays = 7;
chomp(my $curstamp = `TZ="UTC" date -d "$fdays days" +"%Y%m%d%H%M00"`);
chomp(my $stpstamp = `TZ="UTC" date -d "$tdays days" +"%Y%m%d%H%M00"`);
if (($_[0] > $curstamp) && ($_[1] < $stpstamp)) {
if (defined($deleted)) {
my #deleted = split /,/, $deleted;
foreach (#deleted) {
if ($_ ne $_[0]) {
push(#entry, \%ehash);
}
}
}
else {
push(#entry, \%ehash);
}
}
print Dumper #entry;
This works mostly as expected:
$VAR1 = {
'DURATION' => '5',
'STARTSTAMP' => '20141122230000',
'UID' => '20141114T010539Z--1092363482',
'LASTMOD' => '20141118214419',
'STARTDATE' => '2014-11-22 23:00:00',
'EMAIL' => 'xxxxxxxxxxxxx',
'ENDDATE' => '2014-11-23 04:00:00',
'CN' => 'xxxxxxxxxxx',
'ENDSTAMP' => '20141123040000',
'KEY' => 'xxxxxxxxxxxxxxxxxx'
};
$VAR2 = {
'EMAIL' => 'xxxxxxxxxxxxx',
'ENDDATE' => '2014-11-23 23:00:00',
'ENDSTAMP' => '20141123230000',
'KEY' => 'xxxxxxxxxxx',
'CN' => 'xxxxxxxxxxxxxx',
'STARTDATE' => '2014-11-23 19:00:00',
'LASTMOD' => '20141118205901',
'UID' => '20141114T010456Z--1092363482',
'DURATION' => '4',
'STARTSTAMP' => '20141123190000'
};
$VAR3 = $VAR2;
Where is the $VAR3 = $VAR2 coming from?
My guess is that this section is the culprit:
foreach (#deleted) {
if ($_ ne $_[0]) {
push(#entry, \%ehash);
}
}
If you have several values in the array, the if-statement can be true twice, and thus push a value twice. Unless this is wanted behaviour, I would make sure that only one value is pushed. You can do this by using grep instead:
if (grep { $_ ne $_[0] } #deleted) {
push #entry, \%ehash;
}
Note that this replaces the foreach loop.
Your array #entry contains hash references. Data::Dumper is saying that the first and second elements of the array refer to two different hashes, while the third refers to the same hash as the second.
You don't show where #entry comes from, but I would expect all three elements to be references to %ehash.
The problem is that, if you keep pushing a reference to %ehash onto #entry, they all point to the same data item, and the intermediate states of the hash won't be recorded.
Unless you mean entrytoarray to push only one copy of %ehash (in which case there's a separate problem that we can't see) you need to fix it by either writing
push #entry, { %ehash }
which copies the hash and returns a reference to the copy, or you can declare and populate %ehash inside the foreach loop, which will create a new hash each time around the loop.

Invalid argument supplied for foreach() unpacking Facebook array in Laravel 4

I am trying to store the FBIDs of a Facebook user's friends in the column of a mysql database. I've tried looking up other answer on this issue, and I have tried to implement it (in Laravel 4). Here is what I have done:
In the Facebook.php file, one of the providers:
'friends' => 'https://graph.facebook.com/me/friends?access_token='.$token->access_token
In my Oauth2 Controller:
$friends_list = $user['friends'];
$friends_list_array = json_decode($friends_list,true);
$arr= $friends_list_array['data'];
$friend_ids_arr = array();
foreach($arr as $friend) {
$friend_ids_arr[] = $friend['id'];
}
$friend_ids = implode("," , $friend_ids_arr);
And then I want to store the $friend_ids object in a "text" column in my database. However, when running this, I keep getting the error: Invalid argument supplied for foreach()
But it is very clearly being supplied an array as it should. Is there something I'm not seeing? Thank you for your help.
Actually the returned result is a json, the returned object should look something like this
{
"id": "xxxxxxx",
"name": "Sheikh Heera",
"friends": {
"data": [
{ "name": "RaseL KhaN", "id": "xxx" },
{ "name": "Yizel Herrera", "id": "xxx" }
],
"paging": {
"next": "https://graph.facebook.com/xxx/friends?limit=..."
}
}
}
After you json_decode
$user = json_decode($user, true);
It should look something like
Array
(
[id] => xxxxxxx
[name] => Sheikh Heera
[friends] => Array
(
[data] => Array
(
[0] => Array
(
[name] => RaseL KhaN
[id] => xxx
)
[1] => Array
(
[name] => Yizel Herrera
[id] => xxx
)
)
[paging] => Array
(
[next] => https://graph.facebook.com/xxx/friends?limit=...
)
)
)
So, now you can
$friends_list = $user['friends'];
$data = $friends_list['data'];
Make sure your $data array is not empty and then loop
if(count($data)) {
$friend_ids_arr = array();
foreach($data as $friend) {
$friend_ids_arr[] = $friend['id'];
}
}
So, the foreach will run only when $data has items in it.
Update: It may help you
$url = "https://graph.facebook.com/me?fields=id,name,friends&access_token=YOUR_ACCESS_TOKEN";
$contents = json_decode(file_get_contents($url), true);
$friends = $contents['friends'];
$friend_ids_arr[]
foreach($friends['data'] as $friend)
{
$friend_ids_arr[] = $friend['id'];
}

Resources