how to add a new value to a multidimensional array keeping the key if preg_match found a match with the files in my directory ?
<?php
if(isset($_POST['submit'])){
$txt1 = $_FILES['filetxt']['tmp_name'];
$txt2 = $_FILES['filetxt']['name'];
$g = glob('./upload/img/*.*');
foreach ($txt2 as $var) {
$rap = explode(' ', $var);
$zc = count($rap);
for ($i=0; $i < $zc; $i++) {
$str = $rap[$i];
$ext = substr($str, 0, strrpos($str, "."));
$pattern = "/$ext/i";
if(preg_match_all($pattern, $str, $matches)) {
$array = array_map('array_filter', $matches);
$array = array_filter($array);
}
}
var_dump($array);
}
}
Here's result of $array (pattern for preg_match):
array(1) {
[0]=>
string(12) "dropshipping"
}
array(1) {
[0]=>
string(9) "standards"
}
array(1) {
[0]=>
string(8) "boutique"
}
array(1) {
[0]=>
string(7) "vitrine"
}
I would like to apply preg_match on each value of the txt2 array and recursively insert the corresponding values if the condition is true.
here's result of txt2 array:
array(4) {
[0]=>
string(22) "Texte dropshipping.txt"
[1]=>
string(24) "Texte site standards.txt"
[2]=>
string(22) "Texte sur boutique.txt"
[3]=>
string(30) "Texte sur les site vitrine.txt"
}
My Answer:
You can achieve this by using a recursive function to iterate through the multidimensional array and check if any of the values match the pattern using `preg_match`. If a match is found, you can add a new value to the array while keeping the key intact.
Here's an example code snippet to demonstrate this:
php
function addValueIfMatch(&$array, $pattern, $newValue) {
foreach ($array as $key => &$value) {
if (is_array($value)) {
addValueIfMatch($value, $pattern, $newValue);
} else {
if (preg_match($pattern, $value)) {
$array[$key] = $value;
$array['new_value'] = $newValue;
}
}
}
}
$pattern = '/\.txt$/'; // Pattern to match files ending with .txt
$newValue = 'new_value_to_add';
// Your multidimensional array
$array = [
'file1' => 'file1.txt',
'file2' => 'file2.jpg',
'nested_array' => [
'file3' => 'file3.txt',
'file4' => 'file4.png'
]
];
addValueIfMatch($array, $pattern, $newValue);
print_r($array);
In this code snippet, the `addValueIfMatch` function recursively iterates through the multidimensional array and checks if any of the values match the specified pattern using `preg_match`. If a match is found, it adds a new key-value pair to the array while keeping the original key intact.
You can adjust the pattern and new value according to your requirements.
Rate this post
4 of 5 based on 9023 votesComments