I have listed an example below. What I need is for $key to return the actual index number (position) in the array during the loop, but instead it is returning Array. The same code works fine when given a single dimension array, but not in the example below.
GIVEN:
$screenshots would be similar to the following with only more entries.
Array
(
[0] => Array
(
[screenshot_id] => 871
[image_filename] => DSCF0124.JPG
)
)
PHP:
//build in clause & binding using selected array from above
$prefix = $in_clause = '';
$binding_clause = array();
foreach($screenshots as $key)
{
$in_clause .= $prefix.':selected_'.$key;
$prefix = ', ';
$binding_clause[':selected_'.$key] = $key['screenshot_id'];
}
RESULT:
$inclause = :selected_Array
$binding_clause =
Array
(
[:selected_Array] => 871
)
EXPECTED:
$inclause = :selected_0
$binding_clause =
Array
(
[:selected_0] => 871
)
Just because you call it $key doesn't make it a key. You need the key and the value (inner array):
foreach($screenshots as $key => $value)
{
$in_clause .= $prefix.':selected_'.$key;
$prefix = ', ';
$binding_clause[':selected_'.$key] = $value['screenshot_id'];
}
You need to tell it that you want the KEY and the VALUE.
like this:
foreach($screenshots as $key=>$screenShot)
That will get you the key and the value.
You just need to change your foreach to cast keys and values
foreach($screenshots as $key => $val)
Now the key is in your $key variable while you can access elements with $val array, for example $key['screenshot_id']
You can have a check to documentation examples here
Try:
foreach($screenshots as $key => $screenshot)
{
$in_clause .= $prefix.':selected_'.$key;
$prefix = ', ';
$binding_clause[':selected_'.$key] = $screenshot['screenshot_id'];
}
Read more about PHP foreach: http://php.net/manual/en/control-structures.foreach.php
Related
I have strings in following format:
$strings[1] = cat:others;id:4,9,13
$strings[2] = id:4,9,13;cat:electric-products
$strings[3] = id:4,9,13;cat:foods;
$strings[4] = cat:drinks,foods;
where cat means category and id is identity number of a product.
I want to split these strings and convert into arrays $cats = array('others'); and $ids = array('4','9','13');
I know that it can be done by foreach and explode function through multiple steps. I think I am somewhere near, but the following code does not work.
Also, I wonder if it can be done by preg_match or preg_split in fewer steps. Or any other simpler method.
foreach ($strings as $key=>$string) {
$temps = explode(';', $string);
foreach($temps as $temp) {
$tempnest = explode(':', $temp);
$array[$tempnest[0]] .= explode(',', $tempnest[1]);
}
}
My desired result should be:
$cats = ['others', 'electric-products', 'foods', 'drinks';
and
$ids = ['4','9','13'];
One option could be doing a string compare for the first item after explode for cat and id to set the values to the right array.
$strings = ["cat:others;id:4,9,13", "id:4,9,13;cat:electric-products", "id:4,9,13;cat:foods", "cat:drinks,foods"];
foreach ($strings as $key=>$string) {
$temps = explode(';', $string);
$cats = [];
$ids = [];
foreach ($temps as $temp) {
$tempnest = explode(':', $temp);
if ($tempnest[0] === "cat") {
$cats = explode(',', $tempnest[1]);
}
if ($tempnest[0] === "id") {
$ids = explode(',', $tempnest[1]);
}
}
print_r($cats);
print_r($ids);
}
Php demo
Output for the first item would for example look like
Array
(
[0] => others
)
Array
(
[0] => 4
[1] => 9
[2] => 13
)
If you want to aggregate all the values in 2 arrays, you can array_merge the results, and at the end get the unique values using array_unique.
$strings = ["cat:others;id:4,9,13", "id:4,9,13;cat:electric-products", "id:4,9,13;cat:foods", "cat:drinks,foods"];
$cats = [];
$ids = [];
foreach ($strings as $key=>$string) {
$temps = explode(';', $string);
foreach ($temps as $temp) {
$tempnest = explode(':', $temp);
if ($tempnest[0] === "cat") {
$cats = array_merge(explode(',', $tempnest[1]), $cats);
}
if ($tempnest[0] === "id") {
$ids = array_merge(explode(',', $tempnest[1]), $ids);
}
}
}
print_r(array_unique($cats));
print_r(array_unique($ids));
Output
Array
(
[0] => drinks
[1] => foods
[3] => electric-products
[4] => others
)
Array
(
[0] => 4
[1] => 9
[2] => 13
)
Php demo
I don't generally recommend using variable variables, but you are looking for a sleek snippet which uses regex to avoid multiple explode() calls.
Here is a script that will use no explode() calls and no nested foreach() loops.
You can see how the \G ("continue" metacharacter) allows continuous matches relative the "bucket" label (id or cat) by calling var_export($matches);.
If this were my own code, I'd probably not create separate variables, but a single array containing id and cat --- this would alleviate the need for variable variables.
By using the encountered value as the key for the element to be added to the bucket, you are assured to have no duplicate values in any bucket -- just call array_values() if you want to re-index the bucket elements.
Code: (Demo) (Regex101)
$count = preg_match_all(
'/(?:^|;)(id|cat):|\G(?!^),?([^,;]+)/',
implode(';', $strings),
$matches,
PREG_UNMATCHED_AS_NULL
);
$cat = [];
$id = [];
for ($i = 0; $i < $count; ++$i) {
if ($matches[1][$i] !== null) {
$arrayName = $matches[1][$i];
} else {
${$arrayName}[$matches[2][$i]] = $matches[2][$i];
}
}
var_export(array_values($id));
echo "\n---\n";
var_export(array_values($cat));
All that said, I probably wouldn't rely on regex because it isn't very readable to the novice regex developer. The required logic is much simpler and easier to maintain with nested loops and explosions. Here is my adjustment of your code.
Code: (Demo)
$result = ['id' => [], 'cat' => []];
foreach ($strings as $string) {
foreach (explode(';', $string) as $segment) {
[$key, $values] = explode(':', $segment, 2);
array_push($result[$key], ...explode(',', $values));
}
}
var_export(array_unique($result['id']));
echo "\n---\n";
var_export(array_unique($result['cat']));
P.s. your posted coding attempt was using a combined operator .= (assignment & concatenation) instead of the more appropriate combined operator += (assignment & array union).
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.
Here is my array: [["STR_License_Driver",1],["STR_License_Truck",0],["STR_License_Pilot",1],["STR_License_Firearm",0],["STR_License_Rifle",0]]
My goal is to make an array or string (unsure of best method) called results where the value of the licenses is 1.
For example: The results should be something like: STR_Licenses_Driver, STR_Licenses_Pilot.
I am currently using PHP Version 7, and Laravel Version 5.5
JSON Decode the $this->license and do the loop.
Whole code:
$licenses = $this->licenses;//This is your posted array string
$result = json_decode($licenses);
$licenses_with_1 = array();
foreach($result as $i){
foreach($i as $key => $value){
if($value == 1){
$licenses_with_1[] = $i[0];
}
}
}
print_r($licenses_with_1);
Result:
Array ( [0] => STR_License_Driver [1] => STR_License_Pilot )
I remember Python on your data structure.
Try my solution:
https://3v4l.org/nrfqZ
$licenses = [["STR_License_Driver",1],["STR_License_Truck",0],["STR_License_Pilot",1],["STR_License_Firearm",0],["STR_License_Rifle",0]];
Map over filtered array having second item equal to 1 to get the license names.
$filterVal = 1;
$licenseNames = array_map(
function ($item) { return $item[0]; },
array_filter(
$licenses,
function ($item) use ($filterVal) { return $item[1] === $filterVal; }
)
);
Then implode array of license names to join by glue string.
echo implode($licenseNames, ', ');
I'm trying to do a function that search a value inside a multidimensional array and adding up the value from the findings. The array is as below
$arr = array (
'MY106782'=> array ('code'=>"MY106782",'totalSales'=>"5625.00",'SponsorID'=>"MY246913"),
'MY126192'=> array ('code'=>"MY126192",'totalSales'=>"5625.00",'SponsorID'=>"MY126637"),
'MY128276'=> array ('code'=>"MY128276",'totalSales'=>"3180.00",'SponsorID'=>"MY106782"),
'MY157278'=> array ('code'=>"MY157278",'totalSales'=>"5625.00",'SponsorID'=>"MY477500"),
'MY167585'=> array ('code'=>"MY167585",'totalSales'=>"5625.00",'SponsorID'=>"MY106782")
);
I'm trying to search all 'MY106782' inside the "SponsorID" array, get the 'totalSales' value when found and add the values if the is multiple records
Since your array is a key value pair arrays, you have to determine which key are you looking for. Check this:
$sponsor_id = "MY106782";
$total_sales = 0;
$arr = array (
'MY106782'=> array ('code'=>"MY106782",'totalSales'=>"5625.00",'SponsorID'=>"MY246913"),
'MY126192'=> array ('code'=>"MY126192",'totalSales'=>"5625.00",'SponsorID'=>"MY126637"),
'MY128276'=> array ('code'=>"MY128276",'totalSales'=>"3180.00",'SponsorID'=>"MY106782"),
'MY157278'=> array ('code'=>"MY157278",'totalSales'=>"5625.00",'SponsorID'=>"MY477500"),
'MY167585'=> array ('code'=>"MY167585",'totalSales'=>"5625.00",'SponsorID'=>"MY106782")
);
foreach($arr as $values) {
if($values["SponsorID"] == $sponsor_id) {
$total_sales += (float)$values["totalSales"];
}
}
echo $sponsor_id . " - " . $total_sales;
try to something like this
$i = 0;
foreach ($arr as $key => $value) {
if ($value['SponsorID'] == 'MY106782') {
$i++;
}
}
Output: 2
You can use below script if key is exist only once time in a array.
$arr = array (
'MY106782'=> array ('code'=>"MY106782",'totalSales'=>"5625.00",'SponsorID'=>"MY246913"),
'MY126192'=> array ('code'=>"MY126192",'totalSales'=>"5625.00",'SponsorID'=>"MY126637"),
'MY128276'=> array ('code'=>"MY128276",'totalSales'=>"3180.00",'SponsorID'=>"MY106782"),
'MY157278'=> array ('code'=>"MY157278",'totalSales'=>"5625.00",'SponsorID'=>"MY477500"),
'MY167585'=> array ('code'=>"MY167585",'totalSales'=>"5625.00",'SponsorID'=>"MY106782")
);
$key_to_check = 'MY157278';
if (array_key_exists($key_to_check, $arr)) {
echo $arr[$key_to_check]['totalSales'];
}else{
echo "key not found."
}
I have this the values of in my array as
$itsthere = (item1-0-100, item2-0-50, item3-0-70, item4-0-50, item5-0-100);
If the user enter the value item3 he has to get 70 which is present in array. I tried alot using explode but its not showing proper value. Can any one help me.
Try with:
$itsthere = array(
'item1-0-100',
'item2-0-50',
'item3-0-70',
'item4-0-50',
'item5-0-100'
);
$search = 'item3';
$output = '';
foreach ( $itsthere as $value ) {
if ( strpos($search . '-', $value) === 0 ) {
$output = explode('-', $value)[2];
break;
}
}
When you say item3 are you refering to the third position or the item3 as array key? I think you can create a assoc array and make item names as key
$isthere = array('item1' => '0-100', 'item2' => '0-50' ,'item3' => '0-70', ....,);
echo $isthere['item3']; // This would give you the value.
If you only want to know if this key is in the array use array_key_exists.
Try this :
$item = 'item3';
$itsthere = array('item1-0-100', 'item2-0-50', 'item3-0-70', 'item4-0-50', 'item5-0-100');
foreach($itsthere as $there)
{
$exp = explode('-',$there);
if($exp[0] == 'item3') {
echo $val = $exp[2];
};
}