Question

I have a array like so

$tags = 

Array
(
   [0] => Array
    (
        [0] => [first_name] [last_name]
        [2] => [city],[state] [zipcode]
    )

 )

i also have a list like so

$array_list = 

  [0] => Array
    (
        [first_name] => Bob
        [last_name] => Johnson
        [city] => mycity
        [state] => NY
        [zipcode] => 911564
    )

[1] => Array
    (
        [first_name] => John
        [last_name] => Doe
        [city] => New York
        [state] => NY
        [zipcode] => 9115

    )

[2] => Array
    (
        [first_name] => James
        [last_name] => Belt
        [city] => Los Angeles
        [state] => CA
        [zipcode] => 915456
    )

I basically want to replace all the tags inside of the brackets with the actual value from the array. I tried the following but it only seems to be returning a single value back correctly

 foreach($tags as $key=>$value) {
     $data[$key] = preg_replace_callback('/[\[|<](.*)[\]\)]/U', 'replace_text', $value);
 }



 function replace_text($matches) {
    foreach ($array_list as $arg) {
       return $args[$matches[1]];

    }        

  }

Im only getting back one result that looks like so

Array
(
   [0] => Array
    (
        [0] => Bob Johnson
        [1] => mycity,NY 911564
    )

)

how can i do it so that i get all the results back in a array with all the correct values

i tried to change the function replace_text to set the values to a array and return the array like so

 function replace_text($matches) {
    foreach ($array_list as $arg) {
       $new_array[]= $args[$matches[1]];

    }    

     return $new_array;

  }

but this returns

 Array
(
[0] => Array
    (
        [0] => Array Array
        [1] => Array
        [2] => Array,Array Array
    )

 )

I should also add that all this content is dynamic so one time it may be [first_name] and the next [name_first] or somethign else which is why i need to fine the brackets in each and replace the text inside of brackets with what matches the array.

Was it helpful?

Solution

What do you think about this:

$output = array();
foreach($array_list as $arraykey => $array) {
     foreach($tags[0] as $tagkey => $tag)
        $output[$arraykey][$tagkey] = preg_replace_callback('/[\[|<](.*)[\]\)]/U', 'replace_text', $tag);
}

function replace_text($matches) {
    global $arraykey, $array_list;
    return $array_list[$arraykey][$matches[1]];
}

If it's not good for you, can you show the expected $output?

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top