Duplicates in Associative array - php

My foreach is entering an array in the second level of my $bad_email array, something like this
["vlley#.rsr.com"] { ["name"]=> "Woo Hilley", ["amount"]=> "125.16"}
["vey#.rsr.com"] { ["name"]=> "Shoo Moo", ["amount"]=> "12.16"}
If I try to enter the same value like ["vlley#.rsr.com"] { ["name"]=> "Woo Hilley", ["amount"]=> "125.16"} again I want it to run specific code. Im not sure how to fix this. The code Im running seems to work when the name is the same but I want the email, name and amount to all match before it fires. Help please
$bad_email = array();
$i = 0;
foreach ($id_array as $key => $id) {
$bad_email[$email][name] =$name;
$bad_email[$email][amount] = $amount;
if ($bad_email[$email][$amount], $bad_email[$email])) {
// DO CODE HERE!!!!
$i++;
}
}
$email, $name, and $amount are all pulled from an api call

This worked...
$bad_email = array();
$temp_email = array();
foreach ($id_array as $key => $id) {
$temp_email =$bad_email;
$bad_email[$email][name] =$name;
$bad_email[$email][amount] = $amount;
if ($bad_email[$email][amount] == $temp_email[$email][amount]){
// DO CODE HERE!!!!
}
}
}

Related

PHP Associated Arrays only showing first letter of value

I have a HTML form with multiple inputs.
I have the below php code to get them inputs and put them in an associated array.
However, when dumping the Associated array the value only shows the first letter...
<?php
$valueArray=array
(
"servername"=>'',
"serverlocation"=>'',
"servertype"=>'',
"serverdescription"=>''
);
foreach($valueArray as $key => $value)
{
if (isset($_POST[$key]))
{
$postValue = $_POST[$key];
$actualValue = $postValue;
$valueArray[$key][$value] = $actualValue;
}
}
var_dump($valueArray);
?>
This is what is dumped -
array(4) { ["servername"]=> string(1) "d" ["serverlocation"]=> string(1) "K" ["servertype"]=> string(1) "P" ["serverdescription"]=> string(1) "t" } post
How do i get it to store the whole string, and not just the first letter?
If you want to fill the valueArray with the content of the POST request you have to do this:
$valueArray=array
(
"servername"=>'',
"serverlocation"=>'',
"servertype"=>'',
"serverdescription"=>''
);
foreach($valueArray as $key => $value)
{
if (isset($_POST[$key]))
{
$postValue = $_POST[$key];
$valueArray[$key] = $postValue;
}
}
var_dump($valueArray);
I think you ar wrong with this line:
$valueArray[$key][$value] = $actualValue;
Try this
$valueArray=array
(
"servername"=>'',
"serverlocation"=>'',
"servertype"=>'',
"serverdescription"=>''
);
$postData=array
(
"servername"=>'serverName',
"serverlocation"=>'serverLocation',
"servertype"=>'serverType',
"serverdescription"=>'serverDescription'
);
foreach($valueArray as $key => $value)
{
if (isset($postData[$key]))
{
$postValue = $postData[$key];
$actualValue = $postValue;
$valueArray[$key] = $actualValue;
}
}
var_dump($valueArray);

Laravel 5.4: how to iterate through request array?

My request data represents an array of new and existing items. I'm trying to through this array to update and create items.
This is how I retrieve the array:
$userInput = $request->all();
foreach( $userInput['items'] as $key=>&$item){
Later in the code I update an existing item:
$updateItem = Item::find($item['id']);
$updateItem->number = $item['number'];
$updateItem->save();
But $item['number'] seems to contain old input from previous updates and not the value I entered last time.
How can I loop through request data in Laravel ?
This is the whole code as I run it (want to get rid of confusion):
$userInput = $request->all();
// checking $userInput here
// I can see the new value in the array
foreach( $userInput['items'] as $key=>$item){
if($item['delete'] == 1) {
Item::where('order_id',$order->id)
->where('id',$item['id'])
->delete();
} else {
if(empty($item['id'])) {
} else {
$updateItem = Item::find($item['id']);
$updateItem->number = $item['id'];
$updateItem->save();
}
}
}
This is an input from html (just to show I checked the form also, the data comes just fine):
<input id="basicItemNumber-31" class="form-control" name="items[31][number]" placeholder="Unique number" value="31" type="text">
It's likely that somewhere inside your for you've inadvertently changed the value of your underling $item as you pass it by reference (using the & before the variable name.)
It's considered bad practice by some or most people as it can lead to "unexpected" behaviour, For example. take the sample code below that loops through an array of $items twice once by reference and once by value.
<?php
$items = ['one','two','three'];
foreach ($items as &$item) {
//do nothing.
}
foreach ($items as $item) {
//do nothing again.
}
var_dump($items);
//outputs
array(3) {
[0]=>
string(3) "one"
[1]=>
string(3) "two"
[2]=>
&string(3) "two"
}
Try something like this as it will keep your scope local:
$request['items']->each(function($item, $key) use ($order) {
if ($item->delete) {
Item::where('order_id',$order->id)
->where('id',$item['id'])
->delete();
} else {
if (!empty($item['id'])) {
$updateItem = Item::find($item['id']);
$updateItem->number = $item['id'];
$updateItem->save();
}
}
});

Change value within array based on input in php

I am trying to locale the correct sub-array in order to change the count, if a specific value is present more than once.
I have the following code:
$trending = [];
foreach($hashtags as $hashtag) {
if(in_array($hashtag->hashtag, $hashtags))
{
array_search()
}
else {
array_push($trending, [
'hashtag' => $hashtag->hashtag,
'counts' => '1'
]);
}
}
This gives me the following example outout:
array(3) {
[0]=> array(2)
{
["hashtag"]=> "foobar"
["counts"]=> "1"
}
[1]=> array(2)
{
["hashtag"]=> "hashtags"
["counts"]=> "1"
}
[2]=> array(2)
{
["hashtag"]=> "imageattached"
["counts"]=> "1"
}
}
So in the foreach loop and the if statement, i want to check for dublicates of hashtags, e.g. if the hashtag foobar exists more than one time, I don't want to create another dublicate in the array, but I want to change the count to 2
How do I find the correct "sub"-array, and change the count of this to 2, if a hashtag is present within $hashtags more than once??
The idea is, that I at the end can sort these arrays, and get the hashtag that is most common, by looking at the count.
If you change the structure of your output, you could do something like this:
$trending = [];
foreach($hashtags as $tag) {
if (isset($trending[$tag])) $trending[$tag]++;
else $trending[$tag] = 1;
}
Which would result in $trending having the structure
array(2) {
["foobar"] => 1,
["hashtags"] => 2
}
Which could then be looped through with
foreach($trending as $tag => $count) {
echo $tag . ' appears ' . $count . ' times.' . PHP_EOL;
}
The PHP method array_count_values might be of some help.
http://php.net/manual/en/function.array-count-values.php
Have you considered using a keyed array?
$trending = array();
foreach($hashtags as $hashtag) {
if(!isset($trending[$hashtag])){
$trending[$hashtag] = 1;
}else{
$trending[$hashtag] += 1;
}
}
By using a keyed array, there is no duplication and you can easily check how frequently a hashtag is used by just accessing $trending[$hashtag]. Additionally, you can get the list of all hashtags in the trending array using $allHashtags = array_keys($trending);.
Of course, if your project specifications do not allow for this, then by all means, use a different approach, but that would be the approach I would take.
It can be more linear of you can change your array structure but for the current this should work.
$trending = [];
$checker = true;
foreach($hashtags as $hashtag) {
foreach ($trending as $key =>$value) {
if($value["hashtag"] == $hashtag->hashtag){
$trending[$key]["counts"]++;
$checker = false;
}
}
if($checker) {
array_push($trending, [
'hashtag' => $hashtag->hashtag,
'counts' => '1'
]);
}
$checker = true;
}

PHP - fetch value of specified key pair in mulit-dimensional array

hopefully a easy one for you,
my sql query is returning a mulit-dimensional array, I need to access only one key the is nested on the second level but cant figure out how.
here is my function.
public function get_visitor_id($id)
{
$this->db->where('mobile',$id);
$this->db->or_where('email',$id);
$this->db->select('uid');
$result = $this->db->get('visitors');
if ($result)
{
foreach ($result->result() as $key=>$value){
$array[$key] = $value;
}
var_dump($array);
return $array;
}
}
The array returned is
{ [0]=> object(stdClass)#20 (1) { ["uid"]=> string(2) "24" } }
I only need the value of ['uid'] so in essence if I was to echo get_visitor_id() it would evaluate to "24".
Thanks for you help.
Cheers
try changing foreach() func to:
foreach($result as $res){
$res = $res->fetch_assoc();
$array['uid'] = $res['uid'];}
EDIT: in case of this didn't work then try while loop:
while($res = $result->fetch_assoc()){
$array['uid'] = $res['uid'];
}

Foreach array with different values

Need little help, i get always stupid errors, when i try to do this, i want to foreach array, and inside that do a for loop, is this possible?
Here is my code
$image = new SimpleImage();
$slike=array($_FILES['slika1']['tmp_name'],$_FILES['slika2']['tmp_name'],$_FILES['slika3']['tmp_name'],$_FILES['slika4']['tmp_name']);
$koliko = count($slike);
foreach ($slike as $slika) {
for ($i = 1; $i <= $koliko; $i++)
{
$slicica="../images/usluge/".mysql_insert_id()."-".$i.".jpg";
$image->load($slika);
$image->resizeToWidth(800);
$image->save($slicica);
}
}
I want to get new pictures with this name, example.If last id was 2 i want to get this filenames etc
2-1.jpg
2-2.jpg
2-3.jpg
2-4.jpg
Still with my code i dont get correct values :(
Or maybe there is easy way to do that :)
I think what you need is to replace your following line:
$image->load($slika);
for this one:
$image->load($slike[$i-1]);
you probably have a problem in you foreach as if we do a var_dump on an array we will see the following :
array(3) { [0]=> string(5) "test1" [1]=> string(4) "tes2" [2]=> string(5) "test3" }
so you need to change it to :
foreach ($slike as $key => $slika) {
you can also use move_uploaded_file to achieve what you are trying to do and use linux command convert :
foreach ($slike as $key => $slika) {
for ($i = 1; $i <= $koliko; $i++)
{
$slicica="../images/usluge/".mysql_insert_id()."-".$i.".jpg";
if(move_uploaded_file(slika,slicica)){
exec("convert $slicica -resize 200 $slicica");
}else{die('problem loading the file');}
}
}
$i=1;
// insert into mysql table..
// [...]
$mysqlId = mysql_insert_id();
foreach ( $_FILES as $key => $value) {
$slicica="../images/usluge/".$mysqlId."-".$i.".jpg";
if(move_uploaded_file($_FILES[$key]["tmp_name"],slicica)){
$image->load($slicica);
$image->resizeToWidth(800);
$image->save($slicica);
}
else {
// error handling
}
$i++;
}

Categories