Array - Grab Names: Url and Caption

Asked

Viewed 31 times

0

I have dynamic inputs with Names my_image[url] and my_image[caption]

<input name="my_image[url]" type="hidden" value="<?php echo $imgurl['url'];?>"/>
<input name="my_image[caption]" type="text" value="<?php echo $imgurl['caption'];?>">

Even inserted several images and captions dynamically, inside the isset o $ _POST ['my_image'] is capturing only 1 image and 1 caption:

if (isset($_POST['my_image'])){ 
    update_option('imagens_inicio',array($_POST['my_image']);
    echo '<pre>'; var_dump($_POST['my_image']);echo '</pre>';
}

array(1) {
  [0]=>
  array(2) {
    ["url"]=>
    string(96) "http://localhost/theme/wp-content/uploads/2017/08/4e07dd2bd752b989e9b4687129982977.jpg"
    ["caption"]=>
    string(0) "test text"
  }
}

How do I make the array to be created in a continuous sequence:

url[]
caption[]
url[]
caption[]

I appreciate help

  • I believe the field name should follow the format my_image[0][url] and my_image[0][caption], incrementing the value of 0 for each dynamic field inserted on the page.

  • @Andersoncarloswoss It did not work, I asked the question in English tbm, but I did not understand the proposed solution see: link

  • In my opinion the solution presented in Soen is good, renaming the inputs to url[] and caption[], which creates two independent arrays with automatic sequential numbering. Naturally it will change the way you read them, as indicated in that reply

  • @Isac ah tah I now understood the logic of his reply, but I didn’t understand that part: ($url, $caption) { return compact('url', 'caption'); the variables $url and $caption are implied that refers to the post url and post caption? 'url' and 'caption' in the single quotes tbm is implied that?

  • They refer to the parameters of array_map. It uses the function array_map php that in his example takes two arrays, the , $_POST['url'], $_POST['caption']) and interconnects them at the expense of the function compact. Compact takes two strings with the name of the variables to put in a new array.

  • Right I get it, but the var_dump($data); is returning null

  • I finally got it! $_POST['url']; and $_POST['caption']; because directly in the array_map wasn’t working. thanks a lot @Isac

Show 2 more comments

1 answer

0


With help in the Soen, in the question I asked there too, and help from @Isac here from Sopt I managed to solve:

 if (isset($_POST['url'])){ 

          $url = $_POST['url'];
          $caption = $_POST['caption'];

          $data = array_map(function ($url, $caption) {
                return compact('url', 'caption');
           }, $url, $caption);

           update_option('imagens_inicio',$data);

    }

Browser other questions tagged

You are not signed in. Login or sign up in order to post.