- Изменить исходные значения массива в foreach
- Решение
- Другие решения
- PHP Change Array Values with foreach
- How
- Syntax
- Example
- Note
- Next chapter.
- Php foreach change array value
- Unpacking nested arrays with list()
- How foreach change original array values in php
- Join the world's most active Tech Community!
- Welcome back to the World's most active Tech Community!
- Subscribe to our Newsletter, and get personalized recommendations.
- TRENDING CERTIFICATION COURSES
- TRENDING MASTERS COURSES
- COMPANY
- WORK WITH US
- DOWNLOAD APP
- CATEGORIES
- CATEGORIES
Изменить исходные значения массива в foreach
У меня есть массив массивов, которые содержат ключ массива со значением, вот пример:
$text = [ [ 0 => ['Andi', 'NOB', false], 1 => ['menginap', 'V', false], 2 => ['di', 'PREP', false], 3 => ['Hotel', 'N', false], 4 => ['Neo', 'NE', false], 5 => ['Malioboro', 'NE', false], 6 => ['selama', 'N', false], 7 => ['satu', 'NUM', false], 8 => ['minggu', 'N',false] ] ];
и у меня также есть этот массив:
Теперь, если массив элементов флага находится на текстовом ключе, тогда я заменю третий элемент с false на true.
Например :
$ flag [0] = 3, тогда я изменю текст с ключом 3 на:
foreach($text as $index => &$tok) < foreach ($tok as $tokkey =>&$tokvalue) < foreach($flag as $key =>$value) < if($value == $tokkey)< $tokvalue[2] = true; >> > >
Но это не изменило все.
Любая помощь высоко ценится, спасибо.
Решение
foreach($text as $index => &$tok) < foreach ($tok as $tokkey =>&$tokvalue) < foreach($flag as $key =>$value) < if($value == $tokkey)< $val = explode(",",$tokvalue); $val[2] = true; $tokvalue = implode(",",$val); >> > >
Другие решения
как насчет прямого доступа к $text ?
Таким образом, вам не нужно использовать ссылки.
$text = [ [ ['Andi', 'NOB', false], ['menginap', 'V', false], ['di', 'PREP', false], ['Hotel', 'N', false], ['Neo', 'NE', false], ['Malioboro', 'NE', false], ['selama', 'N', false], ['satu', 'NUM', false], ['minggu', 'N.', false] ] ]; $flag = [3,4,5,6]; foreach ($text as $index => $token) < // outer list foreach ($token as $i =>$t) < //inner list foreach ($flag as $key) < if ($key == $i) $text[$index][$i][2] = true; >> > print_r($text);
И я положу мои два цента, а также:
попробуйте, это будет работать для вас:
$text = [ [ '0' => 'Andi,NOB,false', '1' => 'menginap,V,false', '2' => 'di,PREP,false', '3' => 'Hotel,N,false', '4' => 'Neo,NE,false', '5' => 'Malioboro,NE,false', '6' => 'selama,N,false', '7' => 'satu,NUM,false', '8' => 'minggu,N,false' ] ]; $flag = [3,4,5,6] ; foreach($text as $k=> $value) < foreach($flag as $key=>$val) < $kk[] = explode(',',$value[$val]); $kk[$key][2] = 'true'; $kkk[] = implode(',',$kk[$key]); >> echo ''; print_r($kkk);
распечатать массив, который мы хотим изменить ложное значение на истинное значение.
приведенный ниже код для отображения всех данных с заменой на требуемый вывод:
$text = [ [ ['Andi', 'NOB', 'false'], ['menginap', 'V', 'false'], ['di', 'PREP', 'false'], ['Hotel', 'N', 'false'], ['Neo', 'NE', 'false'], ['Malioboro', 'NE', 'false'], ['selama', 'N', 'false'], ['satu', 'NUM', 'false'], ['minggu', 'N.', 'false'] ] ]; $flag = [3,4,5,6]; foreach ($text as $k => $value) < foreach ($value as $kk =>$val) < foreach ($flag as $key) < if ($key == $kk) $text[$k][$kk][2] = 'true'; >> > echo ''; print_r($text);
Здесь мы используем array_walk достичь желаемого результата.
Я предполагаю, что это будет массив,
$text = [ 0 => ['Andi', 'NOB', false], 1 => ['menginap', 'V', false], 2 => ['di', 'PREP', false], 3 => ['Hotel', 'N', false], 4 => ['Neo', 'NE', false], 5 => ['Malioboro', 'NE', false], 6 => ['selama', 'N', false], 7 => ['satu', 'NUM', false], 8 => ['minggu', 'N.',false], ]; $flag = [0 => 3, 1 => 4, 2 => 5, 3 => 6]; foreach ($text as $key => &$value) < if(in_array($key, $flag))< $value[2] = true; >> echo ""; print_r($text);
Пожалуйста, проверьте вывод Вот
Нет более чистого / более прямого (защищенного от ошибок) способа, чем:
Код: (демонстрация ) Самый простой способ
$flag=3; // index if(isset($text[0][$flag][2])) // make sure the element exists
Если у вас есть несколько флагов:
$flags=[3,6,7]; // indices foreach($flags as $flag) < if(isset($text[0][$flag][2]))// make sure the element exists >
Любой метод, который зацикливает ваш $text массив подвергается риску выполнения бесполезных итераций. Это будет неэффективной / плохой практикой кодирования.
Вы можете перебрать массив флагов и приравнять значение этих ключей к массиву требуемых значений.
$flag = [1,3]; $text = [ 0 => ['a', 'x', true], 1 => ['a', 'y', false], 2 => ['x', 'd', true], 3 => ['x', 's', true], 4 => ['a', 'x', false], ]; foreach ($flag as $key) < if (isset($text[$key])) < $text[$key][2] = true; >>
PHP Change Array Values with foreach
When using foreach, the values inside the loop are copies of the values.
If you change the value, you're not affecting the value in the original array. The following example code illustrates this:
/*from j a v a2 s .co m*/ $authors = array( "Java", "PHP", "CSS", "HTML" ); // Displays "Java PHP Javascript HTML"; foreach ( $authors as $val ) < if ( $val == "CSS" ) $val = "Javascript"; echo $val . " "; > print_r ( $authors ); ?>
The code above generates the following result.
Although $val was changed from "CSS" to "Javascript" within the loop, the original $authors array remains untouched.
How
To modify the array values, we need to get foreach() to return a reference to the value in the array, rather than a copy.
Syntax
To work with references to the array elements, add a & (ampersand) symbol before the variable name within the foreach statement:
Example
Here's the previous example rewritten to use references:
//from j a v a2s .com $authors = array( "Java", "PHP", "CSS", "HTML" ); foreach ( $authors as & $val ) < if ( $val == "CSS" ) $val = "Javascript"; echo $val . " "; > unset( $val ); print_r ( $authors ); ?>
The code above generates the following result.
This time, the third element's value in the $authors array is changed from "CSS" to "Javascript" in the array itself.
Note
The unset($val) ensures that the $val variable is deleted after the loop has finished.
When the loop finishes, $val still holds a reference to the last element. Changing $val later in our code would alter the last element of the $authors array. By unsetting $val, we avoid potential bug.
Next chapter.
What you will learn in the next chapter:
Php foreach change array value
The foreach construct provides an easy way to iterate over arrays. foreach works only on arrays and objects, and will issue an error when you try to use it on a variable with a different data type or an uninitialized variable. There are two syntaxes:
foreach (iterable_expression as $value) statement foreach (iterable_expression as $key => $value) statement
The first form traverses the iterable given by iterable_expression . On each iteration, the value of the current element is assigned to $value .
The second form will additionally assign the current element's key to the $key variable on each iteration.
Note that foreach does not modify the internal array pointer, which is used by functions such as current() and key() .
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.
$arr = array( 1 , 2 , 3 , 4 );
foreach ( $arr as & $value ) $value = $value * 2 ;
>
// $arr is now array(2, 4, 6, 8)
unset( $value ); // break the reference with the last element
?>?php
Reference of a $value and the last array element remain even after the foreach loop. It is recommended to destroy it by unset() . Otherwise you will experience the following behavior:
// without an unset($value), $value is still a reference to the last item: $arr[3]
foreach ( $arr as $key => $value ) // $arr[3] will be updated with each value from $arr.
echo " < $key >=> < $value >" ;
print_r ( $arr );
>
// . until ultimately the second-to-last value is copied onto the last value
// output:
// 0 => 2 Array ( [0] => 2, [1] => 4, [2] => 6, [3] => 2 )
// 1 => 4 Array ( [0] => 2, [1] => 4, [2] => 6, [3] => 4 )
// 2 => 6 Array ( [0] => 2, [1] => 4, [2] => 6, [3] => 6 )
// 3 => 6 Array ( [0] => 2, [1] => 4, [2] => 6, [3] => 6 )
?>
It is possible to iterate a constant array's value by reference:
Note:
foreach does not support the ability to suppress error messages using @ .
Some more examples to demonstrate usage:
/* foreach example 1: value only */
?php
foreach ( $a as $v ) echo "Current value of \$a: $v .\n" ;
>
/* foreach example 2: value (with its manual access notation printed for illustration) */
$i = 0 ; /* for illustrative purposes only */
foreach ( $a as $v ) echo "\$a[ $i ] => $v .\n" ;
$i ++;
>
/* foreach example 3: key and value */
$a = array(
"one" => 1 ,
"two" => 2 ,
"three" => 3 ,
"seventeen" => 17
);
foreach ( $a as $k => $v ) echo "\$a[ $k ] => $v .\n" ;
>
/* foreach example 4: multi-dimensional arrays */
$a = array();
$a [ 0 ][ 0 ] = "a" ;
$a [ 0 ][ 1 ] = "b" ;
$a [ 1 ][ 0 ] = "y" ;
$a [ 1 ][ 1 ] = "z" ;
foreach ( $a as $v1 ) foreach ( $v1 as $v2 ) echo " $v2 \n" ;
>
>
/* foreach example 5: dynamic arrays */
foreach (array( 1 , 2 , 3 , 4 , 5 ) as $v ) echo " $v \n" ;
>
?>
Unpacking nested arrays with list()
It is possible to iterate over an array of arrays and unpack the nested array into loop variables by providing a list() as the value.
foreach ( $array as list( $a , $b )) // $a contains the first element of the nested array,
// and $b contains the second element.
echo "A: $a ; B: $b \n" ;
>
?>
The above example will output:
You can provide fewer elements in the list() than there are in the nested array, in which case the leftover array values will be ignored:
foreach ( $array as list( $a )) // Note that there is no $b here.
echo " $a \n" ;
>
?>
The above example will output:
A notice will be generated if there aren't enough array elements to fill the list() :
foreach ( $array as list( $a , $b , $c )) echo "A: $a ; B: $b ; C: $c \n" ;
>
?>
The above example will output:
Notice: Undefined offset: 2 in example.php on line 7 A: 1; B: 2; C: Notice: Undefined offset: 2 in example.php on line 7 A: 3; B: 4; C:
How foreach change original array values in php
- All categories
- ChatGPT (11)
- Apache Kafka (84)
- Apache Spark (596)
- Azure (145)
- Big Data Hadoop (1,907)
- Blockchain (1,673)
- C# (141)
- C++ (271)
- Career Counselling (1,060)
- Cloud Computing (3,469)
- Cyber Security & Ethical Hacking (162)
- Data Analytics (1,266)
- Database (855)
- Data Science (76)
- DevOps & Agile (3,608)
- Digital Marketing (111)
- Events & Trending Topics (28)
- IoT (Internet of Things) (387)
- Java (1,247)
- Kotlin (8)
- Linux Administration (389)
- Machine Learning (337)
- MicroStrategy (6)
- PMP (423)
- Power BI (516)
- Python (3,193)
- RPA (650)
- SalesForce (92)
- Selenium (1,569)
- Software Testing (56)
- Tableau (608)
- Talend (73)
- TypeSript (124)
- Web Development (3,002)
- Ask us Anything! (66)
- Others (2,231)
- Mobile Development (395)
- UI UX Design (24)
Join the world's most active Tech Community!
Welcome back to the World's most active Tech Community!
Subscribe to our Newsletter, and get personalized recommendations.
Sign up with Google Signup with Facebook
Thank you for registering Join Edureka Meetup community for 100+ Free Webinars each month JOIN MEETUP GROUP
TRENDING CERTIFICATION COURSES
- DevOps Certification Training
- AWS Architect Certification Training
- Big Data Hadoop Certification Training
- Tableau Training & Certification
- Python Certification Training for Data Science
- Selenium Certification Training
- PMP® Certification Exam Training
- Robotic Process Automation Training using UiPath
- Apache Spark and Scala Certification Training
- Microsoft Power BI Training
- Online Java Course and Training
- Python Certification Course
TRENDING MASTERS COURSES
- Data Scientist Masters Program
- DevOps Engineer Masters Program
- Cloud Architect Masters Program
- Big Data Architect Masters Program
- Machine Learning Engineer Masters Program
- Full Stack Web Developer Masters Program
- Business Intelligence Masters Program
- Data Analyst Masters Program
- Test Automation Engineer Masters Program
- Post-Graduate Program in Artificial Intelligence & Machine Learning
- Post-Graduate Program in Big Data Engineering
COMPANY
WORK WITH US
DOWNLOAD APP
CATEGORIES
CATEGORIES
- Cloud Computing
- DevOps
- Big Data
- Data Science
- BI and Visualization
- Programming & Frameworks
- Software Testing © 2023 Brain4ce Education Solutions Pvt. Ltd. All rights Reserved. Terms & ConditionsLegal & Privacy