Looping a multidimensional array in php - php

I have a multidimensional array like this:
array(2) {
[1]=>
array(3) {
["eventID"]=>
string(1) "1"
["eventTitle"]=>
string(7) "EVENT 1"
["artists"]=>
array(3) {
[4]=>
array(2) {
["name"]=>
string(8) "ARTIST 1"
["description"]=>
string(13) "artist 1 desc"
["links"]=>
array(2) {
[1]=>
array(2) {
["URL"]=>
string(22) "http://www.artist1.com"
}
[6]=>
array(2) {
["URL"]=>
string(24) "http://www.artist1-2.com"
}
}
}
[5]=>
array(2) {
["name"]=>
string(8) "ARTIST 8"
["description"]=>
string(13) "artist 8 desc"
["links"]=>
array(1) {
[8]=>
array(2) {
["URL"]=>
string(22) "http://www.artist8.com"
}
}
}
[2]=>
array(2) {
["ime"]=>
string(8) "ARTIST 5"
["opis"]=>
string(13) "artist 5 desc"
["links"]=>
array(1) {
[9]=>
array(2) {
["URL"]=>
string(22) "http://www.artist5.com"
}
}
}
}
}
[2]=>
array(3) {
["eventID"]=>
string(1) "2"
["eventTitle"]=>
string(7) "EVENT 2"
["artists"]=>
array(3) {
[76]=>
array(2) {
["name"]=>
string(9) "ARTIST 76"
["description"]=>
string(14) "artist 76 desc"
["links"]=>
array(1) {
[13]=>
array(2) {
["URL"]=>
string(23) "http://www.artist76.com"
}
}
}
[4]=>
array(2) {
["name"]=>
string(8) "ARTIST 4"
["description"]=>
string(13) "artist 4 desc"
["links"]=>
array(1) {
[11]=>
array(2) {
["URL"]=>
string(22) "http://www.artist4.com"
}
}
}
}
}
}
I would like to make html output like this:
--
EVENT 1
ARTIST 1
artist 1 desc
http://www.artist1.com, http://www.artist1-2.com
ARTIST 8
artist 8 desc
http://www.artist8.com
ARTIST 5
artist 5 desc
http://www.artist5.com
--
EVENT 2
ARTIST 76
artist 76 desc
http://www.artist76.com
ARTIST 4
artist 4 desc
http://www.artist4.com
--
etc.
I'm confused about digging deeper and deeper in arrays, especially when my array keys are not sequential numbers but IDs of artist/link/etc.
These arrays will kill me, honestly! =)
Thanks for any help in advance!!!

You're best using the foreach construct to loop over your array. The following is untested and is off the top of my head (and probably therefore not as thought through as it should be!) but should give you a good start:
foreach ($mainArray as $event)
{
print $event["eventTitle"];
foreach ($event["artists"] as $artist)
{
print $artist["name"];
print $artist["description"];
$links = array();
foreach ($artist["links"] as $link)
{
$links[] = $link["URL"];
}
print implode(",", $links);
}
}

The foreach statement will take care of all of this for you, including the associative hashes. Like this:
foreach($array as $value) {
foreach($value as $key => $val) {
if($key == "links") {
}
/* etc */
}
}

I think a good way to approach this is "bottom up", ie. work out what to do with the inner-most values, then use those results to work out the next-level-up, and so on until we reach the top. It's also good practice to write our code in small, single-purpose, re-usable functions as much as possible, so that's what I'll be doing.
Note that I'll assume your data is safe (ie. it's not been provided by a potentially-malicious user). I'll also assume that the keys "ime" and "opi" are meant to match the "name" and "description" of the other arrays ;)
We can ignore the innermost strings themselves, since we don't need to modify them. In that case the inner-most structure I can see are the individual links, which are arrays containing a 'URL' value. Here's some code to render a single link:
function render_link($link) {
return "<a href='{$link['URL']}'>{$link['URL']}</a>";
}
This has reduced an array down to a string, so we can use it remove the inner-most layer. For example:
// Input
array('URL' => "http://www.artist1.com")
// Output
"<a href='http://www.artist1.com'>http://www.artist1.com</a>"
Now we move out a layer to the 'links' arrays. There are two things to do here: apply "render_link" to each element, which we can do using "array_map", then reduce the resulting array of strings down to a single comma-separated string, which we can do using the "implode" function:
function render_links($links_array) {
$rendered_links = array_map('render_link', $links_array);
return implode(', ', $rendered_links);
}
This has removed another layer, for example:
// Input
array(1 => array('URL' => "http://www.artist1.com"),
6 => array('URL' => "http://www.artist1-2.com"))
// Output
"<a href='http://www.artist1.com'>http://www.artist1.com</a>, <a href='http://www.artist1-2.com'>http://www.artist1-2.com</a>"
Now we can go out another level to an individual artist, which is an array containing 'name', 'description' and 'links'. We know how to render 'links', so we can reduce these down to a single string separated by linebreaks:
function render_artist($artist) {
// Replace the artist's links with a rendered version
$artist['links'] = render_links($artist['links']);
// Render this artist's details on separate lines
return implode("\n<br />\n", $artist);
}
This has removed another layer, for example:
// Input
array('name' => 'ARTIST 1',
'description' => 'artist 1 desc',
'links' => array(
1 => array(
'URL' => 'http://www.artist1.com')
6 => array(
'URL' => 'http://www.artist1-2.com')))
// Output
"ARTIST 1
<br />
artist 1 desc
<br />
<a href='http://www.artist1.com'>http://www.artist1.com</a>, <a href='http://www.artist1-2.com'>http://www.artist1-2.com</a>"
Now we can move out a layer to the 'artists' arrays. Just like when we went from a single link to the 'links' arrays, we can use array_map to handle the contents and implode to join them together:
function render_artists($artists) {
$rendered = array_map('render_artist', $artists);
return implode("\n<br /><br />\n", $rendered);
}
This has removed another layer (no example, because it's getting too long ;) )
Next we have an event, which we can tackle in the same way we did for the artist, although I'll also remove the ID number and format the title:
function render_event($event) {
unset($event['eventID']);
$event['eventTitle'] = "<strong>{$event['eventTitle']}</strong>";
$event['artists'] = render_artists($event['artists']);
return implode("\n<br />\n", $event);
}
Now we've reached the outer array, which is an array of events. We can handle this just like we did for the arrays of artists:
function render_events($events) {
$rendered = array_map('render_event', $events);
return implode("\n<br /><br />--<br /><br />", $rendered);
}
You might want to stop here, since passing your array to render_events will give you back the HTML you want:
echo render_events($my_data);
However, if we want more of a challenge we can try to refactor the code we've just written to be less redundant and more re-usable. One simple step is to get rid of render_links, render_artists and render_events since they're all variations on a more-general pattern:
function reduce_with($renderer, $separator, $array) {
return implode($separator, array_map($renderer, $array));
}
function render_artist($artist) {
$artist['links'] = reduce_with('render_link', ', ', $artist['links']);
return implode("\n<br />\n", $artist);
}
function render_event($event) {
unset($event['eventID']);
$event['eventTitle'] = "<strong>{$event['eventTitle']}</strong>";
$event['artists'] = reduce_with('render_artist',
"\n<br /><br />\n",
$event['artists']);
return implode("\n<br />\n", $event);
}
echo reduce_with('render_event', "\n<br /><br />--<br /><br />", $my_data);
If this is part of a larger application, we may want to tease out some more general patterns. This makes the code slightly more complex, but much more re-usable. Here are a few patterns I've spotted:
// Re-usable library code
// Partial application: apply some arguments now, the rest later
function papply() {
$args1 = func_get_args();
return function() use ($args1) {
return call_user_func_array(
'call_user_func',
array_merge($args1, func_get_args()));
};
}
// Function composition: chain functions together like a(b(c(...)))
function compose() {
$funcs = array_reverse(func_get_args());
$first = array_shift($funcs);
return function() use ($funcs, $first) {
return array_reduce($funcs,
function($x, $f) { return $f($x); },
call_user_func_array($first, func_get_args()));
};
}
// Transform or remove a particular element in an array
function change_elem($key, $func, $array) {
if is_null($func) unset($array[$key]);
else $array[$key] = $func($array[$key]);
return $array;
}
// Transform all elements then implode together
function reduce_with($renderer, $separator) {
return compose(papply('implode', $separator),
papply('array_map', $renderer));
}
// Wrap in HTML
function tag($tag, $text) {
return "<{$tag}>{$text}</{$tag}>";
}
// Problem-specific code
function render_link($link) {
return "<a href='{$link['URL']}'>{$link['URL']}</a>";
}
$render_artist = compose(
papply('implode', "\n<br />\n"),
papply('change_elem', 'links', papply('reduce_with',
'render_link',
', '));
$render_event = compose(
papply('implode', "\n<br />\n"),
papply('change_elem', null, 'eventID'),
papply('change_elem', 'eventTitle', papply('tag', 'strong')),
papply('change_elem', 'artists', papply('reduce_with',
$render_artist,
"\n<br /><br />\n")));
echo reduce_with($render_event, "\n<br /><br />--<br /><br />", $my_data);

Related

Getting a specific value from multi-dimensional array [duplicate]

I have a multidimensional array like this:
array(2) {
[1]=>
array(3) {
["eventID"]=>
string(1) "1"
["eventTitle"]=>
string(7) "EVENT 1"
["artists"]=>
array(3) {
[4]=>
array(2) {
["name"]=>
string(8) "ARTIST 1"
["description"]=>
string(13) "artist 1 desc"
["links"]=>
array(2) {
[1]=>
array(2) {
["URL"]=>
string(22) "http://www.artist1.com"
}
[6]=>
array(2) {
["URL"]=>
string(24) "http://www.artist1-2.com"
}
}
}
[5]=>
array(2) {
["name"]=>
string(8) "ARTIST 8"
["description"]=>
string(13) "artist 8 desc"
["links"]=>
array(1) {
[8]=>
array(2) {
["URL"]=>
string(22) "http://www.artist8.com"
}
}
}
[2]=>
array(2) {
["ime"]=>
string(8) "ARTIST 5"
["opis"]=>
string(13) "artist 5 desc"
["links"]=>
array(1) {
[9]=>
array(2) {
["URL"]=>
string(22) "http://www.artist5.com"
}
}
}
}
}
[2]=>
array(3) {
["eventID"]=>
string(1) "2"
["eventTitle"]=>
string(7) "EVENT 2"
["artists"]=>
array(3) {
[76]=>
array(2) {
["name"]=>
string(9) "ARTIST 76"
["description"]=>
string(14) "artist 76 desc"
["links"]=>
array(1) {
[13]=>
array(2) {
["URL"]=>
string(23) "http://www.artist76.com"
}
}
}
[4]=>
array(2) {
["name"]=>
string(8) "ARTIST 4"
["description"]=>
string(13) "artist 4 desc"
["links"]=>
array(1) {
[11]=>
array(2) {
["URL"]=>
string(22) "http://www.artist4.com"
}
}
}
}
}
}
I would like to make html output like this:
--
EVENT 1
ARTIST 1
artist 1 desc
http://www.artist1.com, http://www.artist1-2.com
ARTIST 8
artist 8 desc
http://www.artist8.com
ARTIST 5
artist 5 desc
http://www.artist5.com
--
EVENT 2
ARTIST 76
artist 76 desc
http://www.artist76.com
ARTIST 4
artist 4 desc
http://www.artist4.com
--
etc.
I'm confused about digging deeper and deeper in arrays, especially when my array keys are not sequential numbers but IDs of artist/link/etc.
These arrays will kill me, honestly! =)
Thanks for any help in advance!!!
You're best using the foreach construct to loop over your array. The following is untested and is off the top of my head (and probably therefore not as thought through as it should be!) but should give you a good start:
foreach ($mainArray as $event)
{
print $event["eventTitle"];
foreach ($event["artists"] as $artist)
{
print $artist["name"];
print $artist["description"];
$links = array();
foreach ($artist["links"] as $link)
{
$links[] = $link["URL"];
}
print implode(",", $links);
}
}
The foreach statement will take care of all of this for you, including the associative hashes. Like this:
foreach($array as $value) {
foreach($value as $key => $val) {
if($key == "links") {
}
/* etc */
}
}
I think a good way to approach this is "bottom up", ie. work out what to do with the inner-most values, then use those results to work out the next-level-up, and so on until we reach the top. It's also good practice to write our code in small, single-purpose, re-usable functions as much as possible, so that's what I'll be doing.
Note that I'll assume your data is safe (ie. it's not been provided by a potentially-malicious user). I'll also assume that the keys "ime" and "opi" are meant to match the "name" and "description" of the other arrays ;)
We can ignore the innermost strings themselves, since we don't need to modify them. In that case the inner-most structure I can see are the individual links, which are arrays containing a 'URL' value. Here's some code to render a single link:
function render_link($link) {
return "<a href='{$link['URL']}'>{$link['URL']}</a>";
}
This has reduced an array down to a string, so we can use it remove the inner-most layer. For example:
// Input
array('URL' => "http://www.artist1.com")
// Output
"<a href='http://www.artist1.com'>http://www.artist1.com</a>"
Now we move out a layer to the 'links' arrays. There are two things to do here: apply "render_link" to each element, which we can do using "array_map", then reduce the resulting array of strings down to a single comma-separated string, which we can do using the "implode" function:
function render_links($links_array) {
$rendered_links = array_map('render_link', $links_array);
return implode(', ', $rendered_links);
}
This has removed another layer, for example:
// Input
array(1 => array('URL' => "http://www.artist1.com"),
6 => array('URL' => "http://www.artist1-2.com"))
// Output
"<a href='http://www.artist1.com'>http://www.artist1.com</a>, <a href='http://www.artist1-2.com'>http://www.artist1-2.com</a>"
Now we can go out another level to an individual artist, which is an array containing 'name', 'description' and 'links'. We know how to render 'links', so we can reduce these down to a single string separated by linebreaks:
function render_artist($artist) {
// Replace the artist's links with a rendered version
$artist['links'] = render_links($artist['links']);
// Render this artist's details on separate lines
return implode("\n<br />\n", $artist);
}
This has removed another layer, for example:
// Input
array('name' => 'ARTIST 1',
'description' => 'artist 1 desc',
'links' => array(
1 => array(
'URL' => 'http://www.artist1.com')
6 => array(
'URL' => 'http://www.artist1-2.com')))
// Output
"ARTIST 1
<br />
artist 1 desc
<br />
<a href='http://www.artist1.com'>http://www.artist1.com</a>, <a href='http://www.artist1-2.com'>http://www.artist1-2.com</a>"
Now we can move out a layer to the 'artists' arrays. Just like when we went from a single link to the 'links' arrays, we can use array_map to handle the contents and implode to join them together:
function render_artists($artists) {
$rendered = array_map('render_artist', $artists);
return implode("\n<br /><br />\n", $rendered);
}
This has removed another layer (no example, because it's getting too long ;) )
Next we have an event, which we can tackle in the same way we did for the artist, although I'll also remove the ID number and format the title:
function render_event($event) {
unset($event['eventID']);
$event['eventTitle'] = "<strong>{$event['eventTitle']}</strong>";
$event['artists'] = render_artists($event['artists']);
return implode("\n<br />\n", $event);
}
Now we've reached the outer array, which is an array of events. We can handle this just like we did for the arrays of artists:
function render_events($events) {
$rendered = array_map('render_event', $events);
return implode("\n<br /><br />--<br /><br />", $rendered);
}
You might want to stop here, since passing your array to render_events will give you back the HTML you want:
echo render_events($my_data);
However, if we want more of a challenge we can try to refactor the code we've just written to be less redundant and more re-usable. One simple step is to get rid of render_links, render_artists and render_events since they're all variations on a more-general pattern:
function reduce_with($renderer, $separator, $array) {
return implode($separator, array_map($renderer, $array));
}
function render_artist($artist) {
$artist['links'] = reduce_with('render_link', ', ', $artist['links']);
return implode("\n<br />\n", $artist);
}
function render_event($event) {
unset($event['eventID']);
$event['eventTitle'] = "<strong>{$event['eventTitle']}</strong>";
$event['artists'] = reduce_with('render_artist',
"\n<br /><br />\n",
$event['artists']);
return implode("\n<br />\n", $event);
}
echo reduce_with('render_event', "\n<br /><br />--<br /><br />", $my_data);
If this is part of a larger application, we may want to tease out some more general patterns. This makes the code slightly more complex, but much more re-usable. Here are a few patterns I've spotted:
// Re-usable library code
// Partial application: apply some arguments now, the rest later
function papply() {
$args1 = func_get_args();
return function() use ($args1) {
return call_user_func_array(
'call_user_func',
array_merge($args1, func_get_args()));
};
}
// Function composition: chain functions together like a(b(c(...)))
function compose() {
$funcs = array_reverse(func_get_args());
$first = array_shift($funcs);
return function() use ($funcs, $first) {
return array_reduce($funcs,
function($x, $f) { return $f($x); },
call_user_func_array($first, func_get_args()));
};
}
// Transform or remove a particular element in an array
function change_elem($key, $func, $array) {
if is_null($func) unset($array[$key]);
else $array[$key] = $func($array[$key]);
return $array;
}
// Transform all elements then implode together
function reduce_with($renderer, $separator) {
return compose(papply('implode', $separator),
papply('array_map', $renderer));
}
// Wrap in HTML
function tag($tag, $text) {
return "<{$tag}>{$text}</{$tag}>";
}
// Problem-specific code
function render_link($link) {
return "<a href='{$link['URL']}'>{$link['URL']}</a>";
}
$render_artist = compose(
papply('implode', "\n<br />\n"),
papply('change_elem', 'links', papply('reduce_with',
'render_link',
', '));
$render_event = compose(
papply('implode', "\n<br />\n"),
papply('change_elem', null, 'eventID'),
papply('change_elem', 'eventTitle', papply('tag', 'strong')),
papply('change_elem', 'artists', papply('reduce_with',
$render_artist,
"\n<br /><br />\n")));
echo reduce_with($render_event, "\n<br /><br />--<br /><br />", $my_data);

PHP Arrays - Merge two arrays where a value is added together

I need some more help regarding PHP Arrays and the issue I am having. I have an array like this: -
array(2) {
[0]=>
array(2) {
[0]=>
array(2) {
["count"]=>
string(3) "100"
["id"]=>
int(46)
}
[1]=>
array(2) {
["count"]=>
string(3) "300"
["id"]=>
int(53)
}
}
[1]=>
array(1) {
[0]=>
array(2) {
["count"]=>
string(3) "200"
["id"]=>
int(46)
}
}
}
However, I would like it to look more like this as array: -
array(2) {
[0]=>
array(2) {
["count"]=>
string(3) "300" <--- This has been added from Array 1 and 2
["id"]=>
int(46)
}
[1]=>
array(2) {
["count"]=>
string(3) "300"
["id"]=>
int(53)
}
}
Basically if the same id is in both areas I want the count number to be added to each other but if it's not then it needs to just be left alone and included in the array.
I have used a number of array functions such as array_merge and array_push but I am running out of ideas of how this could work. I have also started working on a foreach with if statements but I just got myself completely confused. I just need a second pair of eyes to look at the issue and see howe it can be done.
Thanks again everyone.
Should work with something like this:
$idToCountArray = array(); //temporary array to store id => countSum
array_walk_recursive($inputArray, function($value,$key) { //walk each array in data structure
if(isset(value['id']) && isset($value['count'])) {
//we have found an entry with id and count:
if(!isset($idToCountArray[$value['id']])) {
//first count for id => create initial count
$idToCountArray[$value['id']] = intval($value['count']);
} else {
//n'th count for id => add count to sum
$idToCountArray[$value['id']] += intval($value['count']);
}
}
});
//build final structure:
$result = array();
foreach($idToCountArray as $id => $countSum) {
$result[] = array('id' => $id, 'count' => ''.$countSum);
}
Please note that I have not testet the code and there is probably a more elegant/performant solution.
You could use something like this:
$end_array = array();
function build_end_array($item, $key){
global $end_array;
if (is_array($item)){
if( isset($item["id"])){
if(isset($end_array[$item["id"]]))
$end_array[$item["id"]] = $end_array[$item["id"]] + $item["count"]*1;
else
$end_array[$item["id"]] = $item["count"]*1;
}
else {
array_walk($item, 'build_end_array');
}
}
}
array_walk($start_array, 'build_end_array');
Here is a fiddle.
Thank you ever so much everyone. I actually worked it by doing this: -
$fullArray = array_merge($live, $archive);
$array = array();
foreach($fullArray as $key=>$value) {
$id = $value['id'];
$array[$id][] = $value['count'];
}
$result = array();
foreach($array as $key=>$value) {
$result[] = array('id' => $key, 'count' => array_sum($value));
}
return $result;

loop through php array alphabetically

I have a PHP Loop that loops through data, i want to be able to echo all of this data alphabetically.
i currently use an array:
$output[]=array();
foreach($WHM_Servers as $whm) {
foreach($server->list_accounts() as $ret) {
$output[]= '<tr class="notfirst">
<td>'.$ret["domain"].'</td>
<td>'.$ret["user"].'</td>
<td>'.CompanyInfoLookup($result["customer"], 'company').'</td>
<td>'.$ret["startdate"].'</td>
<td>'.$ret["starttime"].'</td>
<td>'.$ret["disklimit"].'</td>
<td>'.$ret["diskused"].'</td>
</tr>';
}
}
would i be able to add a key in the array and then echo the array alphabetically from the keys
A few different ways to do this, I chose to write a user defined sort function.
$accounts = array();
$accounts[]['name'] = "Tom";
$accounts[]['name'] = "Frank";
$accounts[]['name'] = "Zed";
$accounts[]['name'] = "Aaron";
function compareNames($a, $b){
return strcmp($a['name'], $b['name']);
}
usort($accounts, "compareNames");
var_dump($accounts);
Output:
array(4) {
[0]=>
array(1) {
["name"]=>
string(5) "Aaron"
}
[1]=>
array(1) {
["name"]=>
string(5) "Frank"
}
[2]=>
array(1) {
["name"]=>
string(3) "Tom"
}
[3]=>
array(1) {
["name"]=>
string(3) "Zed"
}
}
This is a standalone example. To apply it to your example, you need to store the data: $accounts = $server->list_accounts(), sort it: usort($accounts, "compareNames");, and then pass it in to your loop: foreach($accounts as $ret) {

Find matching items in array

Absolutely doing my head in here over something that I'm sure is very simple...
I have 2 arrays.
$post_cats which are categories that any given post is in.
$ad_cats which is an array of categories in which ads are placed.
Basically, if a post has in its array of selected categories, a category that matches an item in the array of ad categories, then it must return the matching value/item.
$post_cats returns this
array(4) {
[0]=> array(1) { ["slug"]=> string(6) "energy" }
[1]=> array(1) { ["slug"]=> string(6) "global" }
[2]=> array(1) { ["slug"]=> string(8) "identify" }
[3]=> array(1) { ["slug"]=> string(5) "south" }
}
and $ad_cats returns this
array(6) {
[0]=> array(1) { ["slug"]=> string(5) "north" }
[1]=> array(1) { ["slug"]=> string(5) "south" }
[2]=> array(1) { ["slug"]=> string(4) "east" }
[3]=> array(1) { ["slug"]=> string(4) "west" }
[4]=> array(1) { ["slug"]=> string(6) "global" }
[5]=> array(1) { ["slug"]=> string(8) "fallback" }
}
The duplicated item there is "south", so in my mind the value of array_intersect($post_cats, $ad_cats); should be an array with a single item - "south", correct?
But its returning, what seems like, everything in either of the arrays... I can't for the life of me get it to work..
Using the above example, I need to return "south" to a variable.
So you are looking for items that are in both arrays? ...
What about something like this:
function find_duplicate($array1, $array2)
{
$list = array();
foreach($array1 as $value1)
{
foreach($array2 as $value2)
{
if($value1 == $value2) $list[] = $value1;
}
}
return $list;
}
The best way is to convert those arrays in arrays array_intersect can work with.
Considering:
$a; // first array
$b; // second array
then you would go with:
$a1 = array();
foreach ($a as $v) $a1[] = $v['slug'];
$b1 = array();
foreach ($b as $v) $b1[] = $v['slug'];
$c = array_intersect($a1, $b1);
PHP functions usually work with more powerful algorithms than what you may think; therefore it's a good choice to let PHP functions handle this kind of things.
This solution uses array_map to get at the values and takes the intersection of that
function mapper($a)
{
return $a['slug'];
}
$set1 = array_map('mapper', $post_cats);
$set2 = array_map('mapper', $ad_cats);
$result = array_intersect($set1, $set2);
PhpFiddle for testing.

PHP: help with array structure

My last question helped me get data from a form into an array. The array is fairly different in structure to anything I've used before. I have multiple records with a textbox and checkbox each. Here is the form data:
array(4) {
["product"]=> array(4) {
[0]=> string(5) "Dummy"
[1]=> string(7) "Dummy 2"
[2]=> string(7) "Dummy 3"
[3]=> string(7) "Dummy 4"
}
["tags"]=> array(4) {
[0]=> string(25) "#enter, #product, #hastag"
[1]=> string(0) ""
[2]=> string(25) "#enter, #product, #hastag"
[3]=> string(25) "#enter, #product, #hastag"
}
["chk"]=> array(2) {
[0]=> string(2) "on"
[2]=> string(2) "on"
}
["submit"]=> string(5) "tweet"
}
I want to get the data from this array into a form such as (only if chk = "on"):
tweet[0]["product"] = "dummy"
tweet[0]["tag"] = "hash tag list here"
tweet[1]["product"] = "dummy3"
tweet[1]["tag"] = "hash tag list here"
Any help most appreciated! :)
First I'd recommend using 1 instead of on. You should try to use numerical values whenever possible as they require less processing. I think you need to readjust your HTML, so you don't do any processing on the PHP side at all...
<input type="checkbox" name="tweet[(YOUR_TWEET_ID)][product]" value="PRODUCT_NAME"/>
<input type="text" name="tweet[(YOUR_TWEET_ID)][tags]" value=""/>
This will cause the form to $_POST exactly how you want it without any additional code.
update
foreach ($_POST['tweet'] as $tweetId => $value) {
//again, it'd be a good idea to use a numerical value here
if (strlen($value['product']) > 0) {
//this tweet was checked, lets do with it what we need
//here's how you'd get the tags
echo $_POST['tweet'][$tweetId]['tags'];
}
}
$finalArray = array();
foreach($array['product'] as $key => $name){
if(!empty($array['chk'][$key])){
$finalArray[] = array(
"product" => $name,
"tag" => $array['tags'][$key]);
};
}
Pretty simple:
$i=0;
foreach ($array['chk'] as $key => $val) {
if ($val == "on") {
$new_array[$i]['product'] = $array['product'][$key];
$new_array[$i++]['tags'] = $array['tags'][$key];
}
}
print_r($new_array);
Should do it, there are other ways, this is just one of them.
foreach ($records['chk'] as $id => $temp) {
$tweet[$id]['product'] = $records['product'][$id];
$tweet[$id]['tag'] = $records['tags'][$id];
}

Categories