php: rename duplicate keys by giving number in foreach - arrays

i have a form data and the data's array like this:
$datas=array("x-1","y-2","y-2","y-3","t-1");
my foreach loop:
foreach($datas as $x => $data){
$data=explode("-",$data);
if($data[0]==$data[0]+1){$n=1;}else{$n=0;}
$keys[$x]=$data[0].$n++;
$vals[$x]=$data[1];
}
i couldn't write the true code, my 3rd line is wrong i think (if($data[0]=$data[0]+1){$n="1";}else{$n="";})
so, i wanna rename the duplicate keys by giving number. my output should be like this:
x=1 y1=1 y2=2 y3=2 t1=1

Try
$datas=array("x-1","y-2","y-2","y-3","t-1");
$i=0;
$n=1;
foreach($datas as $x => $data){
$data=explode("-",$data);
$data2=explode("-",$datas[$i+1]);
if($data[0]==$data2[0])
{
$keys[$x]=$data[0].$n;
$n=$n+1;
}
else
{
$keys[$x]=$data[0].$n;
$n=0;
}
$vals[$x]=$data[1];
$i++;
}

This code has error you use = Which will assign value , not compare it.
also n should be integer not string
To fix that
foreach($datas as $x => $data){
$data=explode("-",$data);
if($keys[$x]==$keys[$x+1]){$n=1;}else{$n=0;}
$keys[$x]=$data[0].$n++;
$vals[$x]=$data[1];
}

if($data[0]=$data[0]+1){$n="1";}else{$n="";}
Use == instead of = for the if statements

Related

Perl array - trying to parse quotes in proper array elements

I have been struggling with this for a while in a Perl script I have. Probably a slam dunk for you Perl experts, and probably should be easier, but I can't quite crack the nut on this. I might be needing to split this, not sure.
My array code as is follows.
while ( my $row = $query_handle->fetchrow_hashref('NAME_lc') ){
push #query_output, $row;
push (#{portfo->{label}},$row->{data},$row->{label});
}
And then my print of the array is as follows:
print "array here--";
print "[";
foreach (#{portfo->{label}}) {
#(#{portfo->{label}},$row->{data});
print "\{\"data\":";
print "".$_.",";
print "\"label\":";
print "\"".$row[1]."\"\},";
}
print "]";
print "\n";
And then my output looks like this:
[{"data":2943,"label":""},{"data":CDI3,"label":""},
{"data":1,"label":""},{"data":COS-COS2,"label":""},
{"data":1087,"label":""},{"data":COS1,"label":""},
{"data":5183,"label":""},{"data":COS2,"label":""},
{"data":2731,"label":""},{"data":CULB,"label":""},{"data":1,"label":""},
{"data":EQUIT,"label":""},{"data":4474,"label":""},
{"data":Network,"label":""},]
I am trying to make the apha-num string array items like CDI3, COS1, COS2, etc in quotes, in the label part. Somehow I'm getting it separated. Meanwhile, I do want the numeric values left with the "data" name pair.
[{"data":2943,"label":""},{"data":"CDI3","label":""},
{"data":1,"label":""},{"data":"COS-COS2","label":""},
{"data":1087,"label":""},{"data":"COS1","label":""},
{"data":5183,"label":""},{"data":"COS2","label":""},
{"data":2731,"label":""},{"data":"CULB","label":""},{"data":1,"label":""},
{"data":"EQUIT","label":""},{"data":4474,"label":""},
{"data":"Network","label":""}]
I'm sure it's a simpler fix that I'm making it but so far no luck. Any tips would be greatly appreciated!
Thanks!
use JSON::XS qw( encode_json );
my #data;
while ( my $row = $query_handle->fetchrow_hashref('NAME_lc') ) {
# If $row->{data} is a number,
# make sure it's stored as a number
# so that it gets serialized as a number.
$row->{data} += 0 if $row->{data} =~ /^\d+\z/;
push #data, $row;
}
print(encode_json(\#data));
Or
my $data = $query_handle->fetchall_arrayref({ data => 1, label => 1 });
for my $row (#$data) {
$row->{data} += 0 if $row->{data} =~ /^\d+\z/;
}
print(encode_json($data));
Or if you ensure the fields names are returned as lowercase[1],
my $data = $query_handle->fetchall_arrayref({});
for my $row (#$data) {
$row->{data} += 0 if $row->{data} =~ /^\d+\z/;
}
print(encode_json($data));
This can be done using $dbh->{FetchHashKeyName} = 'NAME_lc'; or AS `label`.

Can't print contents of hash

Here's how I've set up my hash:
my #keys_i_need = qw(A B C D E F G);
my %keys_i_need = map {$_ => []} #keys_i_need;
foreach my $line (#{$file_arr_ref}) {
my $sub = substr( $line, 0, 1);
if(($sub ne "#") and ($sub ne "")){
my #key_vals = split(/\s+/, $line);
my $key = shift #key_vals;
if(exists $keys_i_need{$key}) {
INFO("key is $key value is " . join(", ", #key_vals));
push (#{$keys_i_need{$key}}, \#key_vals);
DEBUG(Dumper \%keys_i_need);
}
}
}
If I understand this correctly, it's a hash, where each value is an array reference with array references inside the array reference. I don't want to use Dumper because I want to pick out each piece.
I'm trying to read out what's been pulled into the hash but I'm getting an error message that says:
"my" variable $values masks earlier declaration in same statement at /home/rabdelaz/workspace/akatest_5/scripts/Viper/Stragglers.pl line 67.
foreach my $key (keys %$config_options) {
foreach my $arr_ref_of_arr_values (%$config_options{$key}) {
foreach my $values (#$arr_ref_of_arr_values) { #<----------line 67
foreach my $value (#$values) {
INFO("key $key has values $value");
}
}
}
}
This looks right to me. I can't quite figure out what perl is complaining about. Any thoughts?
I see what I did now.
I was confused (once again) by the fact that an array reference is a scalar and not an array. Although, as you can see from my original code I went the wrong direction any way (outside to the hash, rather than inside to the array ref. So my final code should look more like this:
foreach my $key (keys %$config_options) {
foreach my $arr_ref_of_arr_values ($$config_options{$key}) {
foreach my $values (#$arr_ref_of_arr_values) { #<----------line 67
foreach my $value (#$values) {
INFO("key $key has values $value");
}
}
}
}
In the course of debugging, I ended up with this to get the first value of the first array in the first key:
INFO("first value of first array of first key: " . ${${$$config_options{'A'}}[0]}[0]);
I then used this as my guidepost.

php: How to assign an array's values to default table?

Here is my code:
$table=array("a","b","c","d");
$datas=array("a_1","c_8");
foreach($datas as $x => $data){
$data=explode("_",$data);
$keys[$x]=$data[0];
$vals[$x]=$data[1];
}
$key=implode("</td><td>",$keys);
$val=implode("</td><td>",$vals);
echo"<table><tr><td>".$key."</td></tr><tr><td>".$val."</td></tr></table>";
It prints out like this:
a c
1 8
But i want this one:
a b c d
1 8
Your problem is the foreach, it's currently only running 2 times, since the $datas Array only has two entrys. Try using the table Array, just like so:
$table=array("a","b","c","d");
$datas=array("a_1","c_8");
foreach($table as $x => $tab){
$var = "";
foreach($datas as $data){
$data = explode("_", $data);
if($data[0]==$tab){
$var = $data[1];
}
}
$keys[$x]=$tab;
$vals[$x]=$var;
}
$key=implode("</td><td>",$keys);
$val=implode("</td><td>",$vals);
echo"<table><tr><td>".$key."</td></tr><tr><td>".$val."</td></tr></table>";

Write session data with dot notation

I add my session variables like this:
foreach ( $data as $key => $value ) {
$this->Session->write("MyVariable.$key", $value );
}
Is it possible to add element to session variable array without passing the key ?
I mean like this:
$MyArray[] = "apple";
$MyArray[] = "banana";
So is it possible to add like this? Pseudo code:
$this->Session->write('MyVariable'.[], "apple");
$this->Session->write('MyVariable'.[], "banana");
Edit: $data array was for giving an example. The data that will be saved is not array. It is a string. Everytime I add to session variable I don't want to give key by code. I wonder whether is it possible out of the box. In my current codes I make it like this:
$newKey = count( $this->Session->read("MyVariable") );
$this->Session->write("MyVariable.$newKey", "apple");
Hi i guess it should be like this:
foreach ( $data as $key => $value ) {
$this->Session->write('MyVariable.'.$key, $value );
}
You have to place a dot inside the quotation mark.
If you don't want to give the key value each time, then store it as an array like #mark said
$this->Session->write("MyVariable", $data);
If you want to add a new value to the $data array in some other part of your code, you'll have to do something like
$data = $this->Session->read("MyVariable");
$data[] = array('other'=>'value');
$this->Session->write("MyVariable", $data);
Or add the exact key like #mmahgoub said
$this->Session->write("MyVariable".$key, $value);

Json decoding arrays [duplicate]

I have a json string like this:
$fields_string = '
{"fields":
{"customers":[{"name":"john","id":"d1"},
{"name":"mike","id":"d2"},
{"name":"andrew","id":"d3"},
{"name":"peter","id":"d4"}]
}
}'
How can I print each name? I will use them later in a html select options, I know how to do that. But I couldn't get the string out.
Here are something I tried:
$obj = json_decode($fields_string);
$fields_detail = $obj-?{"fields"}->{"customers"};
at this point, I am able to print the customer array out by echo json_encode($fields_detail), but before that, I want to get the name break down using foreach. I tried several times, it didn't work. Can anyone help please.
Thanks!
Customers is an array of objects so iterating over each object and reading the property should work.
foreach ($fields_detail as $customer) {
echo $customer->name;
}
Something like this:
$data = json_decode($fields_string, true); // return array not object
foreach($data['fields']['customers'] as $key => $customer) {
echo $customer['name'];
}
Access the names via fields->customers:
$obj = json_decode($fields_string);
foreach($obj->fields->customers as $customer)
{
echo $customer->name . "\n";
}
Demo
foreach($obj->fields->customers as $fields)
echo $fields->name;

Resources