php add items using an multi dimentional array
开发者_JAVA技巧I have multi-dimensional array like this:
Array
(
[0] => Array
(
[id] => 10184
[user_tags] => tag1
)
)
how do i add more 'user_tags' with comma seperated in an array using php
Thanks
$arr[0]['user_tag'] .= ','.$valueToAdd;
or
$arr[0]['user_tag'] .= ','.implode(',', $valueToAdd); // if its an array
You can add something to your 'user_tags' like this :
$myarray[0]['user_tags'] = 'whatever';
If you have an array of tags like this, you can add it like that :
$tags = array('tag1', 'tag2', 'tag3', 'tag4');
$myarray[0]['user_tags'] = implode(', ', $tags);
But in this case, it is maybe better to store the array directly like said in another comment.
If you want to just add one tag :
$myarray[0]['user_tags'] .= ', '.$mytag;
As a hint, I wouldn't store the usertags in comma separated style, but rather in another array, so that $myArray['user_tags'] = array('tag1, 'tag2', 'tag3', ...);
.
You can then translate between array and csv like this:
$myArray['user_tags_csv'] = implode(',', $myArray['user_tags']);
$myArray['user_tags'] = explode(',', $myArray['user_tags_csv']);
This makes it easier to search the tags for existing ones before you append one.
I use this a lot (esp. with user tags or flags) in connection with an SQL database. With different separators (e.g. ',' ';' '|') I even create hierarchical csv strings which translate into multi-dimensional arrays.
Pro-tip: Store the tags in an associative array like {'tag1'='tag1', 'tag2'='tag2'}
, create it with
$myArray['user_tags'] = array_combine(explode(',', $myArray['user_tags_csv']), explode(',', $myArray['user_tags_csv']);
Then you can use array_key_exists()
as well as array_search()
and many other neat things. I use that a lot.
精彩评论