I have a little problem in my project : I would like display only the key of each array when I click on a element of my list. Dump of my table
For example when I click in "Paupiette", I would like display 0.
I partially succeeded but when I click in a element, I see only the last key (here "1").
Here,you can see the code
$carts = $cartService->getCart($user);
//dump($carts); die;
$mykey = 0;
foreach($carts as $key => $value) {
$mykey = $key;
}
dump($mykey);die;
If you have any idea, thank you a lot
You have multiple choice to display your $keys
the first one is :
$keys = array_keys($carts);
The second is :
foreach ($carts as $key => $value) {
dump($key);
}
if you will display all keys after loop
$myKeys = array();
foreach($carts as $key => $value) {
$myKeys[] = $key;
}
dump($myKeys);die;
If you just want to display the keys, following your coding "style":
foreach ($carts as $key => $value) {
dump($key);
}
If you want to display the keys as comma-separated string, again following your coding "style":
$keys = array_keys($carts); // Get the keys, eg, [0, 1];
$str = implode(', ', $keys); // Convert the array to string, eg, "0, 1"
dump($str);
Related
I have this variable $sid and its output is below.
$sid = $_POST['sid'];
// sid consists values like this.
Array
(
[0] => 1
[1] => 2,3
)
now I need to run a query with this sid 1, 2 and 3. To do that I am using following code:
$ex = array();
foreach ( $sid as $key => $value) {
$ex[] = explode(',', $value);
}
foreach ($ex as $key => $value) {
foreach ($value as $k => $v) {
echo $v;
// my query where sid = $v
}
}
Is there any better way without multiple foreach loop?
Try this:
$ex = explode(',', implode(',', $sid));
foreach ($ex as $v) {
echo $v;
}
Basically, your input is an array of strings of comma-separated values, so, you can merge these strings into single string with comma as separator, and then split whole thing using single explode call.
I'm trying to clean my email database that was imported from an excel table. So there's plenty of bad characters, and even two or three emails in the same cell. I dont want to use a direct database solution as was posted here (T-SQL: checking for email format), because I will do a double check by eye before actually excluding it.
1) First I got all of those emails that weren't good shaped. Then I transformed them on to an array. Note that I'm in laravel ecosystem.
$contato = DB::select("select * from emailstable where outro_email NOT REGEXP '^[a-zA-Z0-9][a-zA-Z0-9._-]*[a-zA-Z0-9]#[a-zA-Z0-9][a-zA-Z0-9._-]*[a-zA-Z0-9]\.[a-zA-Z]{2,4}$'");
$email_array = json_decode(json_encode($email_database_as_object), true);
2) From those, I eliminated all those records that do not have the # symbol on it (empty, null, random phrases), excluding them from the original array:
$corretor = preg_grep("/#/i", array_column($email_array, "email"), PREG_GREP_INVERT);
foreach ($corretor as $key => $value) {
$email_array = array_except($email_array, array($key));
}
But the biggest problem is that when I'm trying to remove the bad characters, the preg_grep assigns to the resulting array, new array keys. Instead of keeping the original ones.
As an exemple:
Original array keys that were filtered: 1,4,10,24,34,65,78 (7 keys)
Assigned keys: 0,1,2,3,4,5,6
On my code, I'm trying to extract the multiple emails that was inserted in one cell, through separators as ";" , ",' and " ", using preg_grep:
$email_corrected = array(); //array to get all of the corrected emails
$corretor = preg_grep("/;/i", array_column($email_array, "outro_email"));
foreach ($corretor as $key => $value) {
$provisorio = explode(';', $value);
$provisorio = array_where($provisorio, function($chave, $valor)
{
return strlen($valor) > 0;
}); //laravel function to take out empty results of explode
$provisorio=array_map('trim',$provisorio);
$email_corrected[$key] = $provisorio; //adds the result to corrected emails
$email_array = array_except($email_array, array($key)); // takes out the result from the original array
}
$corretor = preg_grep("/,/i", array_column($email_array, "outro_email"));
foreach ($corretor as $key => $value) {
$provisorio = explode(',', $value);
$provisorio = array_where($provisorio, function($chave, $valor)
{
return strlen($valor) > 0;
});
$provisorio=array_map('trim',$provisorio);
$email_corrected[$key] = $provisorio;
$email_array = array_except($email_array, array($key));
}
$corretor = preg_grep("/\//", array_column($contato_array, "outro_email"));
foreach ($corretor as $key => $value) {
$provisorio = explode(',', $value);
$provisorio = array_where($provisorio, function($chave, $valor)
{
return strlen($valor) > 0;
});
$provisorio=array_map('trim',$provisorio);
$email_corrected[$key] = $provisorio;
$email_array = array_except($email_array, array($key));
}
But after each preg_grep, the keys from $corretor does not match the original keys from $email_array. As a result, Im not eliminating the correct keys from the original array when doing $email_array = array_except($email_array, array($key));
Thanks in advance.
I have a string that I converted to a multi-dimensional array.
String: 13,4,3|65,1,1|27,3,2
I wanna be able to move 27,3,2 to index 1 for example, so it would become:
13,4,3|27,3,2|65,1,1
Or remove one of those sections.
I know I can unset(), but I'm not sure how to search for an index then move it or unset it.
You can try the below one for interchanging the position of last two elements
$array = [0 => array(13,4,3), 1=>array(65,1,1), 2 => array(27,3,2)];
foreach($array as $key => $value) {
if($key == count($array)-1) {
$array[$key] = $array[$key-1];
$array[$key-1] = $value;
}
}
This is for removing the second element.
$array = [0 => array(13,4,3), 1=>array(65,1,1), 2 => array(27,3,2)];
foreach($array as $key => $value) {
if($key == count($array)-1) {
$array[$key-1] = $value;
unset($array[$key]);
}
}
Loop through the array using foreach
foreach($array as $key => $value)
From key you can get the key and can do whatever you like.
Other wise, you can do this if you know the key
echo $array['pass_key_name_here'];
I would post the entire code, but it is lengthly and confusing, so I'll keep it short and simple. This is complicated for myself, so any help will be greatly appreciated!
These are the values from my Array:
Light Blue1
Blue2
Blue1
Black3
Black2
Black1
The values I need to retrieve from my Array are "Light Blue1", "Blue2" and "Black3". These are the "highest values" for each color.
Something similar to what I'm looking for is array_unique, but that wouldn't work here. So something along those lines that can retrieve each color with its highest number.
Thanks!
Assuming your format is always NameNumber a regex should do the trick for separating the data. This will loop through your data in the order your provide and grab the first element that is different and put it into $vals. I am also assuming your data will always be ordered as your example shows
$data = ['Light Blue1',
'Blue2',
'Blue1',
'Black3',
'Black2',
'Black1'];
$vals = [];
$current = '';
foreach($data as $row) {
if(!preg_match('/(.*)(\d)/i', $row, $matched)) continue;
if($matched[1] != $current) {
$vals[] = $row;
$current = $matched[1];
}
}
The solution using preg_split and max functions:
$colors = ['Light Blue1', 'Blue2', 'Blue1', 'Black3', 'Black2', 'Black1'];
$unique_colors = $result = [];
foreach ($colors as $k => $v) {
$parts = preg_split("/(\d+)/", $v, 0, PREG_SPLIT_DELIM_CAPTURE);
$unique_colors[$parts[0]][] = (int) $parts[1];
}
foreach ($unique_colors as $k => $v) {
$result[] = $k . max($v);
}
print_r($result);
The output:
Array
(
[0] => Light Blue1
[1] => Blue2
[2] => Black3
)
If you pre-sort your array with "natural sorting", then you can loop through the array and unconditionally push values into the result with digitally-trimmed keys. This will effectively overwrite color entries with lesser number values and only store the the highest numbered color when the loop finishes.
Code: (Demo)
natsort($data);
$result = [];
foreach ($data as $value) {
$result[rtrim($value, '0..9')] = $value;
}
var_export(array_values($result));
Or you could parse each string and compare the number against its cached number (if encountered before): (Demo)
$result = [];
foreach ($data as $value) {
sscanf($value, '%[^0-9]%d', $color, $number);
if (!isset($result[$color]) || $result[$color]['number'] < $number) {
$result[$color] = ['value' => $value, 'number' => $number];
}
}
var_export(array_column($result, 'value'));
A related technique to find the highest value in a group
I have an array where I store key-value pair only when the value is not null. I'd like to know how to retrieve keys in the array?
<?php
$pArray = Array();
if(!is_null($params['Name']))
$pArray["Name"] = $params['Name'];
if(!is_null($params['Age']))
$pArray["Age"] = $params['Age'];
if(!is_null($params['Salary']))
$pArray["Salary"] = $params['Salary'];
if(count($pArray) > 0)
{
//Loop through the array and get the key on by one ...
}
?>
Thanks for helping
PHP's foreach loop has operators that allow you to loop over Key/Value pairs. Very handy:
foreach ($pArray as $key => $value)
{
print $key
}
//if you wanted to just pick the first key i would do this:
foreach ($pArray as $key => $value)
{
print $key;
break;
}
An alternative to this approach is to call reset() and then key():
reset($pArray);
$first_key = key($pArray);
It's essentially the same as what is happening in the foreach(), but according to this answer there is a little less overhead.
Why not just do:
foreach($pArray as $k=>$v){
echo $k . ' - ' . $v . '<br>';
}
And you will be able to see the keys and their values at that point
array_keys function will return all the keys of an array.
To obtain the array keys:
$keys = array_keys($pArray);
To obtain the 1st key:
$key = $keys[0];
Reference : array_keys()