How to access an index inside an foreach - php

I need to check if there is a 'CodProduto', so i did:
foreach ($movimentos['CodProduto'] as $value){}
It will run all CodProduto and If it exists i need to do a if inside the foreach to check 2 others fields:
if (!$movimentos['Percentagem'] && !$movimentos['Valor'] {...}
My problem is that i dont know how to access the $movimentos['Percentagem'] and !movimentos['Valor'] items/index or sub-index i dont know how to call it.
$movimentos['Valor'] is an array and i dont know how to check his items at same time as i check $movimentos['Percentagem']
i know there is $movimentos['Valor'][$i] in for but how can i do it in for each? is it possible?

foreach allows you to specify a variable to get the index:
foreach ($movimentos['CodProduto'] as $index => $value) {
if (!$movimentos['Percentagem'][$index] && !$movimentos['Valor'][$index]) {...}
}
However, it's usually easier if you put all the related data in a single array, rather than in separate arrays. So instead of
$movimentos = [
"CodProduto" => [...],
"Percentagem" => [...],
"Valor" => [...],
"ProdutoDesignaceo" => [...]
];
do it like this:
$movimentos = [
["CodProduto" => 1, "Percentagem" => 1, "Valor" => 2, "ProdutoDesignaceo" => "..."],
["CodProduto" => 2, "Percentagem" => 3, "Valor" => 4, "ProdutoDesignaceo" => "..."],
...
];
Then your loop would be like:
foreach ($movimentos as $m) {
if (!$m['Percentagem'] && !$m['Valor']) {...}
}

try this:
foreach ($movimentos['CodProduto'] as $index => $value) {
echo $index
}

You can iterate over the items and get the Index for each item.
Use this index ($i) to access the values from the other arrays while you iterate over the CodProduto sub-array.
foreach ($movimentos['CodProduto'] as $i => $value) {
$percentagem = $movimentos['Percentagem'][$i];
$valor = $movimentos['Valor'][$i];
// Do anything you like with these values here
// E.g.
if (!$percentagem && !$valor) {
// ...
}
}

Related

how to use array_push with key value in a for loop in php

I'm trying to use array_push with key value pair in a for loop in php but I'm not getting anything in there, I only get 2 keys with no values, can anyone see what I'm doing wrong,
any help would be appreciated.
$totalItems = $dataArray["totalItemsCount"];
$linkNamesTaken = array();
for($i=0; $i<$totalItems; $i++) {
array_push($linkNamesTaken[$dataArray["data"][$i]["subMediaType"]], $dataArray["data"][$i]["code"]);
}
print_r($linkNamesTaken);
I'm only getting
[Track] =>
[Album] =>
I'm expecting something like
[Track] => LSD-ThundercloudswithSiaDiploLabrinth-Single
[Album] => DuaLipa-ElectricitywithDuaLipa-Album
the dataArray contains data like the following
{"totalItemsCount": 7,
"data": [
{
"id": "366eff50-d6e2-4038-a091-4b84849c7e9e",
"url": "https://APItestboard.lnk.to/GeorgeEzra-Shotgun-Single",
"code": "GeorgeEzra-Shotgun-Single",
"subMediaType": "Track"
},
... 6 more items here like above
]
}
Here you go with key has subMediaType & value as code in your linkNamesTaken array
$linkNamesTaken = array();
foreach($dataArray['data'] as $k1 => $v1) { //7 loop on key value pair
$linkNamesTaken[$v1['subMediaType']] = $v1['code']; // hopefully key value should be unique.
}
print_r($linkNamesTaken);
O/P
Array
(
[Track] => GeorgeEzra-Shotgun-Single
[New Track] => GeorgeEzra-Shotgun-Double
)
EDIT : see http://php.net/manual/en/function.array-push.php#108118
Maybe you're looking for something like this?
$totalItems = $dataArray["totalItemsCount"];
$linkNamesTaken = array();
foreach($totalItems as $key => $value) {
foreach($value['data'] as $key2 => $value2) {
$linkNamesTaken[]['subMediaType'] = $value2['subMediaType'];
$linkNamesTaken[]['code'] = $value2['code'];
}
}

Undefined index in array element

seem to be experiencing something strange. I am loading an Excel file's data into an array. I am handling things like so
foreach ($data->toArray() as $value) {
dd($value);
if(!empty($value)){
foreach ($value as $v) {
dd($v['id']);
$insert[] = [
'id' => $v['id'],
'name' => $v['name']
];
}
}
}
Now the first dd() (laravel output) produces something like so
array:809 [▼
0 => array:20 [▼
"id" => "123"
"name" => "something"
]
...
So I can see there is an array element called id. The second dd, which calls this array element, produces the output 123
The problem comes where I am filling the array with this data. Although I am still using $v['id'] which works for the output, within the array I get the error
Undefined index: id
Why would this be the case when the index is there?
Thanks
Try to add an if to check if the keys really exist in your array. This will avoid situations when the key does not exist and the Undefined index: id error appear.
foreach ($data->toArray() as $value) {
if(!empty($value)){
foreach ($value as $v) {
if (array_key_exists("id",$v) &&
array_key_exists("name",$v)) {
$insert[] = [
'id' => $v['id'],
'name' => $v['name']
];
}
}
}
}

PHP - how to update values in the multiple dimensional array

I created multiple dimensional array and tried to update count value for certain condition as below but not working.
$test[] = [
'firstNm' => 'luke'
,'lastNm' => 'Lee'
,'count' => 10
];
$test[] = [
'firstNm' => 'John'
,'lastNm' => 'Doe'
,'count' => 20
];
foreach ($test as $test01)
{
if ($test01['firstNm'] === 'John'){
$test01['count'] += 70 ;}
}
Looking forward to your help.
Thank you.
Actually you are increasing the value but missing to reasign to the same array. Try this one.
$test[] = [
'firstNm' => 'luke'
,'lastNm' => 'Lee'
,'count' => 10
];
$test[] = [
'firstNm' => 'John'
,'lastNm' => 'Doe'
,'count' => 20
];
foreach ($test as $key => $test01)
{
if ($test01['firstNm'] === 'John'){
$test[$key]['count'] += 70 ;
}
}
print_r($test);
Borrowing from this answer, which cites the PHP manual page for foreach:
In order to be able to directly modify array elements within the loop precede $value with &. In that case the value will be assigned by reference.1
So you could iterate over the array elements by-reference:
foreach ($test as &$test01)
{
if ($test01['firstNm'] === 'John'){
$test01['count'] += 70 ;
}
}
See this illustrated on Teh Playground.
Otherwise you can iterate using the key=>value syntax:
foreach ($test as $index=>$test01)
{
if ($test01['firstNm'] === 'John'){
$test[$index]['count'] += 70 ;
}
}

Recursively check value empty or not

I have to check if items with keys 2, 3, 4, 5 in the sub array with index 0 are empty or not. If empty, I need to throw an exception.
If not empty, then move to next iteration, checking items with keys 3, 4, 5, 6 in the sub array with index 1, and so on.
Items with keys 0 and 1 will always be empty so nothings need to be done with them.
So, check for items with key > 1 then 4-4 pair check if anyone is empty and then throw an exception.
here is my code
$array = array(
array('0' => '','1' => '','2' => 'Wasatch standard','3' => 'Wasatch standard','4' => '3,5,2','5' => 'English','6' => '','7' => '','8' => ''),
array('0' => '','1' => '','2' => '','3' => 'ThisIsAtest','4' => 'Wasatch standard1','5' => '3,4,5','6' => 'English','7' => '','8' => ''),
array('0' => '','1' => '','2' => '','3' => '','4' => 'Wasatch standard1.1','5' => 'Wasatch standard1.1','6' => '2','7' => 'Mathematics','8' =>''),
);
for($i=0;$i<count($array);$i++){
checkRecursivelyIfEmpty($array[$i],array('2'+$i,'3'+$i,'4'+$i,'5'+$i));
}
function checkRecursivelyIfEmpty($value,$sumValue){
foreach ($sumValue as $k => $v) {
if(empty($value[$v])){
throw new Exception("Error Processing Request");
}
}
}
The following function first checks whether the input is an array indeed, then checks for the indexes to be empty. If not, then it throws an exception. Furthermore, it traverses the array to see if there are inner arrays. If so, then it recursively checks them as well. After the function there is a quick demonstration of usage.
function checkThings($inputArray, $subArray) {
//If it is not an array, it does not have the given indexes
if (!is_array($inputArray)) {
return;
}
//throws exception if one of the elements in question is not empty
foreach ($subArray as $key) {
if ((isset($inputArray[$key])) && (!empty($inputArray[$key]))) {
throw new Exception("My Exception text");
}
}
//checks for inner occurrences
foreach ($inputArray as $key => $value) {
if (is_array($inputArray[$key])) {
checkThings($inputArray[$key], $subArray);
}
}
}
//Calls checkThings for all elements
for ($index = 0; $index < count($myArray); $index++) {
checkThings($myArray[$index], array($index + 2, $index + 3, $index + 4, $index + 5));
}
Use foreach and check using empty($value)
foreach ($array as $key => $value) {
$value = trim($value);
if (empty($value))
echo "$key empty <br/>";
else
echo "$key not empty <br/>";
}
Assuming the array is named $a you can use this code. The outer loops iterates over all the arrays. The inner loop iterates from $i+2 to $i+5 (in the case of $i=0, you get 2, 3, 4 and 5) on the sub arrays. The function empty() checks that the item is set and not equal to false (for instance, an empty string).
for($i=0; $i<count($a); $++)
for($j=$i+2; $j<$i+6; $j++)
if(empty($a[$i][$j]))
//Raise an error!

PHP array unset string

I am trying to unset a group of array keys that have the same prefix. I can't seem to get this to work.
foreach ($array as $key => $value) {
unset($array['prefix_' . $key]);
}
How can I get unset to see ['prefix_' . $key] as the actual variable? Thanks
UPDATE: The $array keys will have two keys with the same name. Just one will have the prefix and there are about 5 keys with prefixed keys:
Array {
[name] => name
[prefix_name] => other name
}
I don't want to remove [name] just [prefix_name] from the array.
This works:
$array = array(
'aa' => 'other value aa',
'prefix_aa' => 'value aa',
'bb' => 'other value bb',
'prefix_bb' => 'value bb'
);
$prefix = 'prefix_';
foreach ($array as $key => $value) {
if (substr($key, 0, strlen($prefix)) == $prefix) {
unset($array[$key]);
}
}
If you copy/paste this code at a site like http://writecodeonline.com/php/, you can see for yourself that it works.
You can't use a foreach because it's only a copy of the collection. You'd need to use a for or grab the keys separately and separate your processing from the array you want to manipulate. Something like:
foreach (array_keys($array) as $keyName){
if (strncmp($keyName,'prefix_',7) === 0){
unset($array[$keyName]);
}
}
You're also already iterating over the collection getting every key. Unless you had:
$array = array(
'foo' => 1,
'prefix_foo' => 1
);
(Where every key also has a matching key with "prefix_" in front of it) you'll run in to trouble.
I'm not sure I understand your question, but if you are trying to unset all the keys with a specific prefix, you can iterate through the array and just unset the ones that match the prefix.
Something like:
<?php
foreach ($array as $key => $value) { // loop through keys
if (preg_match('/^prefix_/', $key)) { // if the key stars with 'prefix_'
unset($array[$key]); // unset it
}
}
You're looping over the array keys already, so if you've got
$array = (
'prefix_a' => 'b',
'prefix_c' => 'd'
etc...
)
Then $keys will be prefix_a, prefix_c, etc... What you're doing is generating an entirely NEW key, which'd be prefix_prefix_a, prefix_prefix_c, etc...
Unless you're doing something more complicated, you could just replace the whole loop with
$array = array();
I believe this should work:
foreach ($array as $key => $value) {
unset($array['prefix_' . str_replace('prefix_', '', $key]);
}

Categories