Jump to content

[SOLVED] trying 3 days - splitting multiple array values with same key


oocuz

Recommended Posts

Hi,

 

I'm learning PHP so be lenient, please  ;)

 

Since 3 days I'm sitting over a problem where I try to split the values of an array element that have the same key.

 

short explanation:

 

I retrieve data from multiple textareas where each textarea can have a different number of entries.

Each textarea represents a different category, and it can be a lot textareas, up to 1000+

 

So it wouldn't make sense to give every textarea a unique name and create a unique variable.

 

That's why I use brackets after the textarea name to create an array where the entries of the textareas are already sorted.

<textarea cols="27" rows="3" name="additionalSpelling[<?php echo $category_id; ?>]" id="additionalSpelling_<?php echo $i; ?>"></textarea>

 

my problem is now when I submit the form and retrieve the data on the next page the array looks like that:

The array keys represent the category id to which the array values belong.

Array ( 
[1] => textarea1_entry1 textarea1_entry2
[2] => textarea2_entry1 textarea2_entry2
[3] => textarea3_entry1 textarea3_entry2
); 

 

Each entry is still seperated by \n

But I need to have the array look like that:

 

array( 
"1" => "textarea1_entry1", 
          "textarea1_entry2",
          "etc."
"2" => "textarea1_entry1", 
          "textarea1_entry2",
          "etc."
"3" => "textarea1_entry1", 
          "textarea1_entry2",
          "etc."
        ),

 

or maybe a little different than that, important is that I can access every entry seperately on the next page of my script where I want to mix these entries with a list of other words in a loop.

 

every value of this array is supposed to be mixed with other words later on, like

 

textarea1_entry1 new word (category 1)

textarea1_entry2 new word (category 1)

 

textarea2_entry1 new word (category 2)

textarea2_entry2 new word (category 2)

          etc. etc.

 

It would be great if somebody could point me in the right direction as I'm almost ready to throw my laptop out of the window  :'(

 

 

thanks a lot!

Link to comment
Share on other sites

Just add an additional set of empty brackets after the field names and the data will be received as a multidimensional array:

<textarea cols="27" rows="3" name="additionalSpelling[<?php echo $category_id; ?>][]" id="additionalSpelling_<?php echo $i; ?>"></textarea>

 

Something like this:

array( 
"1" => array (
    0 => "textarea1_entry1", 
    1 => "textarea1_entry2",
    2 => "etc."
    ),
"2" => array (
    0 => "textarea1_entry1", 
    1 => "textarea1_entry2",
    2 => "etc."
    ),
"3" => array (
    0 => "textarea1_entry1", 
    1 => "textarea1_entry2",
    2 => "etc."
    )
)

Link to comment
Share on other sites

Thank you very much, that solved the first part of my problem, I knew it was something very simple, haha thanks!

 

Only one problem left, the array is now in the correct format, but the entries of the textarea are still not seperated in the array.

 

It looks like this now:

 

Array ( [1] => 
Array ( [0] 
=> textarea1_entry1 textarea1_entry2 [1]
=> textarea2_entry1 textarea2_entry1 [2]
=> textarea3_entry1 textarea3_entry1 [3] 
);

 

 

This is the variable for retrieving the arrays information and my test print:

$additionalSpelling = $_REQUEST['additionalSpelling'];
print_r($additionalSpelling);

 

What would I need to do to receive the array so the values are seperated in the array?

I tried to explode it but if I try to use print_r on this variable then it just prints "array"

Link to comment
Share on other sites

It is already separated - the values are in a sub array.

 

$_POST['additionalSpelling'][1] - this would be an array of all the values that belong to the category with an ID of 1. So...

 

$_POST['additionalSpelling'][1][0] is the first value

$_POST['additionalSpelling'][1][1] is the second value

etc...

 

Try running this on your post data to see all the values categorized

foreach ($_POST['additionalSpelling'] as $cat_id => $value_ary)
{
    echo "<h3>Category ID: ($cat_id}</h3>\n";
    echo "<ul>\n";
    foreach ($value_ary as $value)
    {
        echo "<li>{$value}</li>\n";
    }
    echo "</ul>\n";

}

Link to comment
Share on other sites

Thank you, that helped me to understand how to access an multi-dimensional array.

 

But the problem that the values are not split is still there.

 

Sorry if I didn't explained it well enough, give me another try:

 

at first there's an input field, which represents the general topic

<input type="text" id="<?php echo $i; ?>_keyword" name="keywordGer[]" style="width:450px" value="<?php echo trim(preg_replace('/\ss\s/', '\'s ', preg_replace('/\s\s+/', ' ', preg_replace('/[^\w\344\366\374\304\326\334\337?&]/i'," ", $d[''.$row['db_keyword_field_ger'].''])))); ?>" onKeyDown="charCount('keyword', <?=$i?>)" onKeyUp="charCount('keyword', <?=$i?>)" />
	<div width="221px" style="float:left;margin-left:2px;margin-right:2px;">Additional ways of spelling:
			<br />
				<textarea cols="27" rows="3" name="additionalSpellingGer[<?php echo $d[''.$row['db_keyword_category_id_field'].'']; ?>][]" id="additionalSpelling_<?php echo $i; ?>"></textarea>

the textarea represents additional ways of spelling that topic keyword in the input field, now I need to put only the additional spellings into an array, sorted by A: category and B: the topic of the input field

 

That works almost, only thing doesn't work right now is that if a textarea has several lines, that all lines are put together in the array as only one value, but I need to have each line as seperate value.

 

right now the array looks like this:

Array ( 
[1] => Array ( 
	[0] => line_1 line_2 (category 1, topic1)
	[1] => line_1 line_2 (category 1, topic 2)
	[2] => line_1 line_2 (category 1, topic 3)
	Array ( 
	[0] => line_1 line_2 (category 2, topic 4)
	[1] => line_1 line_2 (category 2, topic 5)
	 ) )

 

 

what I would need now is the array to look like this:

 

	Array ( 
	[1] => Array ( 
			[0] => line_1, (category 1, topic1)
					line_2 (category 1, topic1)
			[1] => line_1, (category 1, topic 2)
					line_2 (category 1, topic 2)
			[2] => line_1, (category 1, topic 3)
					line_2 (category 1, topic 3)
			Array ( 
			[0] => line_1, (category 2, topic 4)
					line_2 (category 2, topic 4)
			[1] => line_1, (category 2, topic 5)
					line_2 (category 2, topic 5)
			 ) )

 

I don't know, would the above be the right format for the array so if I use a loop on it that this part:

[0] => line_1, (category 1, topic1)
	line_2 (category 1, topic1)

 

would be treated as different values?

 

What I want to do later on is looping over this array, and append additional words to the values, depending on in which category they are and which topic they have.

 

At the moment it would do this when I loop over the array to append additional words:

line_1 line_2 + word

 

but I need it like this:

line_1 + word

line_2 + word

 

 

I hope I was able to give you a better understanding about my problem, if you need to know anything else, or more code I'll post it!

 

Thank you.

Link to comment
Share on other sites

You are really confusing the issue here. Your "example" arrays above are not valid so I have no idea what the expected input is supposed to be to determine what you are wanting to do with the input.

 

I guess the only question I need answered is, how can I explode data that was sended from an textfield with square brackets []...?

The fact that you are sending the data as an aray has absoltely no bearing on the issue. POST data is always sent as an array. The method I gave you only makes it a multidimensional array to "group" the data logically and I showed you how to access those values.

 

So, the only issue is what you want to "do" with that data. So, let's forget about the fact that the data is sent as an array. Provide a "real word" example of what the data for one text area will look like and explain/show how you want it processed.

Link to comment
Share on other sites

Ok, sorry for the confusion I've just tried to explain it as detailed as I can but I guess that went wrong  ;)

 

 

inputfield - mainkeyword

harry potter

textarea additional spellings of mainkeyword

harri potter

hary potter

harrypotter

harry poter

 

 

inputfield - mainkeyword

michael jackson

textarea additional spellings of mainkeyword

micheal jackson

michaeljackson

miachael jackson

jackson michael

 

 

this is how my inputfields and textareas look, Harry Potter in the above example has category_id 1, Michael jackson has category_id 2

 

now I want to process this data and put it in an array where the data is stored, sorted after the category and grouped by the mainkeyword.

 

so in the array the data should look like

 

harry potter [category 1]

            harri potter

            hary potter

            harrypotter

            harry poter

 

michael jackson [category 2]

      micheal jackson

      michaeljackson

      miachael jackson

      jackson michael

 

 

I hope this was clearer with less confusion ?

Link to comment
Share on other sites

you will need to loop through each individual textarea and explode the entries on the \n character, presuming that each individual spelling is on a new line:

 

foreach($_POST['additional_spelling'] AS $category => $input)
{
  $separate_entries = explode(chr(10), $input);
  $_POST['additional_spelling'][$category] = $separate_entries;
}

echo '<pre>'.print_r($_POST['additional_spelling'], TRUE).'</pre>';

 

is that more along the lines of what you're looking to do?

Link to comment
Share on other sites

OK, based on this explanation, I'm guessing that the additional brackets aren't needed? Three's only one textarea assoaciated with each text field, right? If so, remove the additional empty brackets from the textarea names.

 

OK, now that the objective is clear, we can find a solution. I created a test page (at the end) that should be replicating your form and which also processes the post data how I believe you want it.

 

If the user inputs the following (bold items are the field labels, Keyword is a text field, add'l spellings is a text area with multi-line input)

Keyword 1: First Keyword

Additional Spellings:

Keyword Number 1

1st Keyword

 

Keyword 2: Second Keyword

Additional Spellings:

Sec. Keyword

2nd Keyword

 

Keyword 3: Third Keyword

Additional Spellings:

3rd Keyword

Keyword Number 3

 

The script processes the data into a multidimensional array as follow:

Array
(
    [0] => Array
        (
            [keyword] => First Keyword
            [spelling] => Array
                (
                    [0] => Keyword Number 1
                    [1] => 1st Keyword
                )
        )

    [1] => Array
        (
            [keyword] => Second Keyword
            [spelling] => Array
                (
                    [0] => Sec. Keyword
                    [1] => 2nd Keyword
                )
        )

    [2] => Array
        (
            [keyword] => Third Keyword
            [spelling] => Array
                (
                    [0] => 3rd Keyword
                    [1] => Keyword Number 3
                )
        )
)

 

I think this is what you want. Here is the code:

<?php

//Process the post data
if (isset($_POST['keyword']))
{
$result = array();
foreach ($_POST['keyword'] as $keywordIdx => $keyword)
{
	$keyword = trim($keyword);
	if (!empty($keyword))
	{
		$addlSpellingPost = trim($_POST['additionalSpelling'][$keywordIdx]);
		$spellingAry = explode("\n", $addlSpellingPost);
		$spellingResult = array();
		foreach ($spellingAry as $spelling)
		{
			$spelling = trim($spelling);
			if (!empty($spelling))
			{
				$spellingResult[] = $spelling;
			}
		}
		$result[] = array(
			'keyword' => $keyword,
			'spelling' => $spellingResult
		);
	}
}
}

?>
<html>
<head>
<title>Members Credits</title>
</head>
<body>

<form name="updateCredits" action="" method="POST">

<?php
for ($i=1; $i<=3; $i++)
{
echo "Keyword {$i}: <input type=\"text\" name=\"keyword[{$i}]\"><br />\n";
echo "Additional Spellings:<br />\n";
echo "<textarea cols=\"27\" rows=\"3\" name=\"additionalSpelling[{$i}]\" id=\"additionalSpelling_{$i}\"></textarea><br /><br />\n";
}
?>

<button type="submit">Submit</button>

</form>

<pre>
<?php
print_r($result);
?>
</pre>

</body>
</html>

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.