i know this is similar with other question, but.
how if we get the data array from db and try to compare those data ?
$x = Video::where('kursus_id', $data)->pluck('slug');
$z = Video::where('kelas_id', $data_id_kelas)
->where('mapel_id', $data_id_mapel)
->pluck('slug');
foreach ($z as $value) {
if (in_array($value, $x)) {
} else {
echo $value.'<br>';
}
}
this throw me an error like in_array() expects parameter 2 to be array, object given.
but when i try to change $x and $z with
$x=["2"]
$z=["1","2","3"]
Thats work. and output is 1 & 3
i think when i use db and give it pluck, this will became the same output when i use regular array like ["1","2","3"].
please correct me if my opinion goes wrong. cz im in study. Thanks before mates
in_array() it 2nd param req. array and you are giving object that's why this error
to fix this you need to use toArray() function in laravel
$x = Video::where('kursus_id', $data)->pluck('slug')->toArray();
then you can use in_array($value, $x)
Related
I'm not familiar with hash/reference syntax with Perl and it makes my eyes hurt trying.
I have the following JSON:
{
"Arg":"Custom_Light state alias protocol",
"Results": [
{
"Name":"Custom_Light",
"Internals": { },
"Readings": {
"protocol": { "Value":"V3", "Time":"2017-01-14 18:49:18" },
"state": { "Value":"off", "Time":"2017-03-05 10:39:50" }
},
"Attributes": { "alias": "Kitchen light" }
} ],
"totalResultsReturned":1
}
How do I directly get the Reading > Protocol Value and Reading > state Value as well as the Attributes > Alias?
I am using the default JSON encoder/decoder and it works splendid. Using Dumper($json) I get all the JSON, but I have no clue how to directly access it without using foreach with all the arrays within arrays in this.
I have tried the following:
my $json = from_json( $readout, { utf8 => 1 } );
print "No. Entries:", scalar(keys($json)); #works, returns 3
my #results = %$json{Results};
Dumper(#results[1]); #I get the Results array
From here it already is ugly. What's that %$ doing there? I thought I could do something like print ${ $json->{'Results'}->[1] }{'Readings'}; but that leads me nowhere.
Give me wisdom. How do I access the Protocol value directly? How do I access the state value directly? And finally, how to get to the alias Attribute?
I don't know what I'm doing but I'm getting somewhere with my $test = %{${%$json{Results}}[0]}{Name}; #I get "Custom_Light", nice. Is this the way to go with a gazillion of weird % and $ just randomly thrown in?
You want
$json->{Results}[0]{Readings}{protocol}{Value}
$json->{Results}[0]{Readings}{state}{Value}
$json->{Results}[0]{Attributes}{alias}
However, since the Results item is an array, you are likely to want to iterate over all of its elements, although in this case there is only one element
I find it useful to extract one level of reference at a time into temporary variables. It would look like this
my $results = $json->{Results};
for my $result ( #$results ) {
my $readings = $result->{Readings};
my $attributes = $result->{Attributes};
printf "Protocol: %s\n", $readings->{protocol}{Value};
printf "State: %s\n", $readings->{state}{Value};
printf "Alias: %s\n", $attributes->{alias};
print "\n";
}
Have a look at perlreftut, perldsc, and perlref, it will help you understand how to access deeply nested structures in Perl.
print "No. Entries:", scalar(keys($json)); #works, returns 3
Actually, this will no longer work. Using keys on a scalar, was an experimental feature added in Perl 5.14 that allowed each, keys, push, pop, shift, splice, unshift, and values to be called with a scalar argument. This experiment was considered unsuccessful, and was removed in 5.23. See also Experimental values on scalar is now forbidden. So, you should dereference the hash reference $json before applying keys:
print "No. Entries:", scalar keys %$json;
As described in perlref, %$ref dereferences the hash reference $ref. Next, lets look at this line:
my #results = %$json{Results};
This actually first creates a new (anonymous) hash ( Result => $json->{Result} ) and then assigns this to #results making #result = ( 'Result', $json->{Result} ). So that is why you now can refer to $json->{Result}[0] as $result[1].
But this is obscure coding, and probably not intended as well. So to return to your question, to get the Value field you could write:
my $value = $json->{Results}[0]{Readings}{state}{Value};
And to get the alias field:
my $alias = $json->{Results}[0]{Attributes}{alias};
I am trying to capture an array from my MongoDB database into my Perl script and read each element. This is something that I thought would be simple, but for some dumb reason it is kicking my rearend.
My MongoDB Document (in part)
"members" : [
"5713b2d46d210e51836de591",
"me",
"you",
"him",
"her"
],
Perl code
$document = $database -> get_collection('my_collection')->find_one({_id => $oid});
#members = $document->{'members'};
print Dumper #members;
foreach $member (#members)
{
print "member = $member\n";
}
exit;
Output I am getting:
$VAR1 = [
'5713b2d46d210e51836de591',
'me',
'you',
'him',
'her'
];
member = ARRAY(0x47fa398)
Looking at the last line I see that I am being passed a reference to the array instead of the values. So I tried accessing via $member[0] or $member[1] but that just returns the same ARRAY(0x*****).
PLEASE HELP, I am sure it is something stupid.
Thanks!
Steven
I'm not familiar with Mongo, but looking at the output, your #members array has one element - an array ref (as you suspected). Since Mongo is returning an arrayref, you're best to store that in a scalar and access it like so;
my $members = $document->{'members'};
print "second item returned is: ", $members->[1];
print "The complete contents:\n";
for my $item ( #$members ) {
print " ", $item;
}
Currently I have this:
<?php
$fn = "file.txt";
$file = file_get_contents("./$fn");
$array = array($file);
?>
An example of whats in the text file:
array(1,4,3,2),array(3,2,1,2),array(5,6,7,8)
However when I print the array or even sizeof($array) it is empty. Whats the deal?
The content of your file is plain text not array data structures. You'll have to parse the content yourself. Here is one way of doing it:
$file_content = "array(1,4,3,2),array(3,2,1,2),array(5,6,7,8)";
$matches = [];
$arrays = [];
if (preg_match_all('~array\(((?:(?:\d+),?)*)\),?~', $file_content, $matches)) {
$arrays = array_map(function ($array) { return explode(',', $array); }, $matches[1]);
}
$arrays now contains arrays as you would expect and you can use count() to check their size.
If you know that your file always contain arrays another way to do it is by using eval.
Another approach
eval('$arrays2 = [' . $file_content . '];');
Now $arrays2 contains the same arrays. There is one subtle difference. The former approach does not cast the values to integers whereas eval does.
Warning: Only use eval() if are 100% sure that you know what goes into the function. Also note that this approach will fail on bad data, whereas the former is a little more resilient.
I have simple XML that I want to read in Perl and make hash containing all read keys.
Consider this code:
my $content = $xml->XMLin("filesmap.xml")->{Item};
my %files = map { $_->{Path} => 1 } #$content;
This snippet works great when XML file contains many Item tags. Then $content is a reference to array. But when there is only one Item I get an error when dereferencing as array. My assumption is that $content is a reference to the scalar, not array.
What is the practice to make sure I get array of values read from XML?
What you need is to not use XML::Simple and then it's really trivial. My favourite for fairly straightforward XML samples is XML::Twig
use XML::Twig;
my $twig = XML::Twig -> new -> parsefile ( 'filesmap.xml' );
my #files = map { $_ -> trimmed_text } $twig -> get_xpath ( '//Path' );
With a more detailed XML sample (and desired result) I'll be able to give you a better answer.
Part of the problem with XML::Simple is it tries to turn an XML data structure into perl data structures, and - because hashes are key-values and unordered but arrays are ordered, it has to guess. And sometimes it does it wrong, and other times it's inconsistent.
If you want it to be consistent, you can set:
my $xml = XMLin( "filesmap.xml", ForceArray => 1, KeyAttr => [], ForceContent => 1 );
But really - XML::Simple is just a route to pain. Don't use it. If you don't like XML::Twig, try XML::LibXML instead.
What I would say you need is a flatten-ing step.
my %files
= map { $_->{Path} => 1 }
# flatten...
map { ref() eq 'ARRAY' ? #$_ : $_ }
$xml->XMLin("filesmap.xml")->{Item}
;
You can do a check and force the return into an array reference if necessary:
my $content = $xml->XMLin("filesmap.xml")->{Item};
$content = ref $content eq 'ARRAY'
? $content
: [$content];
Currently I have an array sort. Sort has only one key / value. The keys and values are always different. This array always has just 1 key/value pair. How do I access both elements dynamically in laravel?
I have already solved this but think it is extremely inefficient.
my current solution
I made a function orderQuery() to return the key name.
function orderQuery() {
foreach (Input::get('sort') as $key => $value) {
return $key; // there is only 1 item in the array but this looks like bad practice
}
}
Then I call it like this to respond to my request
->orderBy(orderQuery(), Input::get('sort.'.orderQuery()))
Is there a better way to do this?
You can use key()
$key = key(Input::get('sort'));
If you want to be save reset the pointer first:
$sort = Input::get('sort');
reset($sort);
$key = key($sort);