mahaidery
mahaidery

Reputation: 611

JS/PHP Array Merge

I have a Form Where users Upload Images and enter title for them and then submit. In order to accomplish it, I integrate the AJAXUPLOADER, it doesn't allow multiple Image Upload at once, but one by one, I don't have problem with it.

On Success, it returns the uploaded file name, what I do, I insert a hidden field containing the Image file name as value. And I insert a text field for users to enter the title.

basically, I wanted to have an array with the multiple file names and title so I put this code:

 input type="text" name="images[][title]" input type="hidden" value="'+response+'" name="images[][url]" 

It works perfectly, but there's a problem. the array structure builds with the above code:

[images] => Array
    (
        [0] => Array
            (
                [title] => Ferrari
            )

        [1] => Array
            (
                [url] => d2339e1d8da95e811c4344eaef226d09.jpg
            )

        [2] => Array
            (
                [title] => Ferrari
            )

        [3] => Array
            (
                [url] => 714208a8c1b819a548a258c33e311e98.jpg
            )

    )

However, I want them in this format:

  [images] => Array
    (
        [0] => Array
            (
                [title] => Ferrari,
                [url] => d2339e1d8da95e811c4344eaef226d09.jpg
            )

        [1] => Array
            (
                [title] => Ferrari,
                [url] => 714208a8c1b819a548a258c33e311e98.jpg
            )

    )

Any quick help will be appreciated!

Upvotes: 0

Views: 212

Answers (2)

Bryan
Bryan

Reputation: 6752

By declaring indices in your input, that array will automatically be built properly for you, no need to do any fancy array merging.

<input type="text" name="images[0][title]" />
<input type="hidden" value="'+response+'" name="images[0][url]" />

<input type="text" name="images[1][title]" />
<input type="hidden" value="'+response+'" name="images[1][url]" />

So on and so forth :) If you're using a PHP loop to declare your inputs, it's as simple as this.

<? for($i = 0; $i < 2; $i++) { ?>
<input type="text" name="images[<?= $i ?>][title]" />
<input type="hidden" value="'+response+'" name="images[<?= $i ?>][url]" />
< } ?>

I hope this helps make your life easier!

Upvotes: 3

Madara&#39;s Ghost
Madara&#39;s Ghost

Reputation: 174957

Name it titles[] and then combine them in PHP.

Example:

<?php
header("Content-type: text/plain"); //Display only
$urls = array(
    "http://example.com/",
    "http://example.com/images/"
);
$titles = array(
    "Example",
    "Example Images"
);
$images = array();
foreach ($urls as $key => $value) {
    $images[$key]["url"] = $value;
    $images[$key]["title"] = $titles[$key];
}

print_r($images);

Upvotes: 0

Related Questions