I need to truncate string and rewrite it back to array
I have got a function where I get data from data base
$data['about_text_list'] = $this->about_text_model->get_array();
I get these fields from data base : id, num, header, text, language
I need to strip_tags and truncate text with function word_limiter
foreach ($data['about_text_list'] as $items)
{
$data['about_text_list']['text'] = word_limiter($items['text'], 100);
$data['about_text_list']['text'] = strip_tags($items['text']);
}
in view I do foreach
<? foreach ($about_text_list as $line) : ?>
<td><?=$line['text']?></td>
<? endforeach; ?>
But I get error, please tell me how to do correct things like this...
In the loop in your controller, you're limiting the word count, then setting that to the value in the array. Then, you're overwriting that value with the strip_tags function. You're using both functions on the same value instead of using the altered values. (And I would strip the tags first, then limit the word count.)
You're also just overwriting the $data['about_text_list']['text'] value each iteration. I'm assuming this needs to be an array of 'text' values? I would create a new array with the updated content and merge your $data['about_text_list'] array with the new array.
Change that loop to this:
$newarray = array();
foreach ($data['about_text_list'] as $key => $value)
{
$item_text = $value['text'];
$altered = strip_tags($item_text);
$newarray[$key]['text'] = word_limiter($altered, 100);
}
$data['about_text_list'] = array_merge($data['about_text_list'], $newarray);
// here, you create a new empty array,
// then loop through the array getting key and value of each item
// then cache the 'text' value in a variable
// then strip the tags from the text key in that item
// then create a new array that mirrors the original array and set
// that to the limited word count
// then, after the loop is finished, merge the original and altered arrays
// the altered array values will override the original values
Also, I'm not sure what your error is (as you haven't told us), but make sure you're loading the text helper to give you access to the word_limiter function:
$this->load->helper('text');
Of course, this all depends on the structure of your array, which I'm guessing at right now.
Related
I have a php array, and inside the array is a reference to another php object with a numerical value.
How can i access the elements in this array without knowing that numerical id (it could be different for each array)?
In the image below, I need to get the values inside field_collection_item like so....
$content['field_image_columns'][0]['entity']['field_collection_item'][133]['field_image']
For the first array key (0) i have done the following...
$i = 0;
while($i <= 2) {
if(isset($content['field_image_columns'][$i])) {
print '<div class="column-' . $i . '">';
foreach ($content['field_image_columns'][$i]['entity']['field_collection_item'] as $fcid => $values) {
// Print field values
}
print '</div>';
}
$i++;
}
Doing a foreach loop for a single array item seems wrong - is there a method i should be using for this use case?
You can select first item of array for example with:
Use array_shift, but it will modify source array:
$cur = array_shift($content['field_image_columns'][$i]['entity']['field_collection_item']);
print $cur['field_image'];
Get keys of array with array_keys and use first element of result as a key
$ks = array_keys($content['field_image_columns'][$i]['entity']['field_collection_item']);
print $content['field_image_columns'][$i]['entity']['field_collection_item'][$ks[0]]['field_image'];
Use current function:
$cur = current($content['field_image_columns'][$i]['entity']['field_collection_item']);
print $cur['field_image'];
As with most programming, there are quite a few ways you could do it. If a foreach works, then it isn't wrong, but it may not be the best way.
// Get the current key from an array
$key = key($array);
If you don't need the key, then you can just get the value from the array.
// Get the current value from an array
$value = current($array);
Both of these will retrieve the first key/value from the array assuming you haven't advanced the pointer.
current, key, end, reset, next, & prev are all array functions that allow you to manipulate an array without knowing anything about the internals. http://php.net/manual/en/ref.array.php
Hard to phrase my question, but here goes. I've got a string like so: "13,4,3|65,1,1|27,3,2". The first value of each sub group (ex. 13,4,3) is an id from a row in a database table, and the other numbers are values I use to do other things.
Thanks to "Always Sunny" on here, I'm able to convert it to a multi-dimensional array using this code:
$data = '13,4,3|65,1,1|27,3,2';
$return_2d_array = array_map (
function ($_) {return explode (',', $_);},
explode ('|', $data)
);
I'm able to return any value using
echo $return_2d_array[1][0];
But what I need to be able to do now is search all the first values of the array and find a specific one and return one of the other value in i'ts group. For example, I need to find "27" as a first value, then output it's 2nd value in a variable (3).
You can loop through the dataset building an array that you can use to search:
$data = '13,4,3|65,1,1|27,3,2';
$data_explode = explode("|",$data); // make array with comma values
foreach($data_explode as $data_set){
$data_set_explode = explode(",",$data_set); // make an array for the comma values
$new_key = $data_set_explode[0]; // assign the key
unset($data_set_explode[0]); // now unset the key so it's not a value..
$remaining_vals = array_values($data_set_explode); // use array_values to reset the keys
$my_data[$new_key] = $remaining_vals; // the array!
}
if(isset($my_data[13])){ // if the array key exists
echo $my_data[13][0];
// echo $my_data[13][1];
// woohoo!
}
Here it is in action: http://sandbox.onlinephpfunctions.com/code/404ba5adfd63c39daae094f0b92e32ea0efbe85d
Run one more foreach loop like this:
$value_to_search = 27;
foreach($return_2d_array as $array){
if($array[0] == $value_to_search){
echo $array[1]; // will give 3
break;
}
}
Here's the live demo.
This question has been asked a thousand times, but each question I find talks about associative arrays where one can delete (unset) an item by using they key as an identifier. But how do you do this if you have a simple array, and no key-value pairs?
Input code
$bananas = array('big_banana', 'small_banana', 'ripe_banana', 'yellow_banana', 'green_banana', 'brown_banana', 'peeled_banana');
foreach ($bananas as $banana) {
// do stuff
// remove current item
}
In Perl I would work with for and indices instead, but I am not sure that's the (safest?) way to go - even though from what I hear PHP is less strict in these things.
Note that after foreach has run, I expected var_dump($bananas) to return an empty array (or null, but preferably an empty array).
1st method (delete by value comparison):
$bananas = array('big_banana', 'small_banana', 'ripe_banana', 'yellow_banana', 'green_banana', 'brown_banana', 'peeled_banana');
foreach ($bananas as $key=>$banana) {
if($banana=='big_banana')
unset($bananas[$key]);
}
2nd method (delete by key):
$bananas = array('big_banana', 'small_banana', 'ripe_banana', 'yellow_banana', 'green_banana', 'brown_banana', 'peeled_banana');
unset($bananas[0]); //removes the first value
unset($bananas[count($bananas)-1]); //removes the last value
//unset($bananas[n-1]); removes the nth value
Finally if you want to reset the keys after deletion process:
$bananas = array_map('array_values', $bananas);
If you want to empty the array completely:
unset($bananas);
$bananas= array();
it still has the indexes
foreach ($bananas as $key => $banana) {
// do stuff
unset($bananas[$key]);
}
for($i=0; $i<count($bananas); $i++)
{
//doStuff
unset($bananas[$i]);
}
This will delete every element after its use so you will eventually end up with an empty array.
If for some reason you need to reindex after deleting you can use array_values
How about a while loop with array_shift?
while (($item = array_shift($bananas)) !== null)
{
//
}
Your Note: Note that after foreach has run, I expected var_dump($bananas) to return an empty array (or null, but preferably
an empty array).
Simply use unset.
foreach ($bananas as $banana) {
// do stuff
// remove current item
unset($bananas[$key]);
}
print_r($bananas);
Result
Array
(
)
This question is old but I will post my idea using array_slice for new visitors.
while(!empty($bananas)) {
// ... do something with $bananas[0] like
echo $bananas[0].'<br>';
$bananas = array_slice($bananas, 1);
}
I have a file containing a two dimensional array and the first term of each nested array is of form id=>2.
I want to extract the array into another file, find the last id in the array, add one to it, create a new array element containing that new id term, add it to the array and then save the edited array back to the original file.
This seemingly simple task has got me beat. I can do the whole thing as long as the processing is done within the original file and I can use file_get_contents() to get the contents of one file into another. But then if I try to use any of the contents I've extracted, eg the array name, php tells me it is undefined.
Grateful if someone could give me a pointer on how to do this.
include 'thefile.php';
$id = 0;
foreach($thearray as $item){
if($item['item_id'] > $id) $id = $item['item_id'];
}
$id++;
$thearray[] = array('item_id' => $id);
file_put_contents('thefile.php','<?php $thearray = '.var_export($thearray, true).';');
I need to get all the elements from a textarea in a HTML form and insert them into the MySQL database using PHP. I managed to get them into an array and also find the number of elements in the array as well. However when I try to execute it in a while loop it continues displaying the word "execution" (inside the loop) over a 1000 times in the page.
I cannot figure out what would be the issue, because the while loop is the only applicable one for this instance
$sent = $_REQUEST['EmpEmergencyNumbers'];
$data_array = explode("\n", $sent);
print_r($data_array);
$array_length = count($data_array);
echo $array_length;
while(count($data_array)){
echo "execution "; // This would be replaced by the SQL insert statement
}
you should use
foreach($data_array as $array)
{
//sql
}
When you access the submitted data in your php, it will be available in either $_GET or $_POST arrays, depending upon the method(GET/POST) in which you have submitted it. Avoid using the $_REQUEST array. Instead use, $_GET / $_POST (depending upon the method used).
To loop through each element in an array, you could use a foreach loop.
Example:
//...
foreach($data_array as $d)
{
// now $d will contain the array element
echo $d; // use $d to insert it into the db or do something
}
Use foreach for the array or decrement the count, your while loop
is a infinite loop if count is >0