How to implode the foreach loop values? - php

I am trying to implode the for each loop to get results like this
["86","87","88"]
Code I am using to achieve results as follows
$tags = [];
$tagsData = $this->Constant_model->getDataOneColumn('snippets_tags', 'snippet_id', $id);
foreach ($tagsData as $data) {
$tag_data = $data->tag_id;
array_push($tags, $tag_data );
}

Use json_encode() to output that format:
echo json_encode($tags);

implode will change your data to a string.
$arr = ['1', '2', '3'];
$imp = implode(', ', $arr);
echo $imp; // output: 1, 2, 3
Probably, what you want is -
$tags = [];
$tagsData = $this->Constant_model->getDataOneColumn('snippets_tags', 'snippet_id', $id);
foreach ($tagsData as $data) {
$tags[] = $data->tag_id;
}
Hope it helps you. :)

Related

Dynamically generating foreach

I'm trying to write a function that do the following :
Let's say i have an array :
$data = array(
array('10','15','20','25'),
array('Blue','Red','Green'),
array('XL','XS')
)
and my result array should be like :
$result = array(
array('10','15','20','25'),
array('Blue','Red','Green','Blue','Red','Green','Blue','Red','Green','Blue','Red','Green')
array('XL','XS','XL','XS','XL','XS','XL','XS','XL','XS','XL','XS','XL','XS','XL','XS','XL','XS','XL','XS','XL','XS','XL','XS','XL','XS','XL','XS','XL','XS','XL','XS','XL','XS','XL','XS','XL','XS','XL','XS','XL','XS','XL','XS','XL','XS','XL','XS')
)
Im stuck with this because i want a function that is able to do this no matter how much array there is in the first array $data
I have only been able to write this, which is what give the $result array :
foreach($data[2] as $value2){
$result[2][] = $value2;
foreach($data[1] as $value1){
$result[1][] = $value1;
foreach($data[0] as $value0){
$result[0][] = $value0;
}
}
}
After a few research, it seems that a recursive function is the way to go in order to dynamically generate those foreach but i can't get it to work.
Thanks for your help.
This is dynamic:
$result[] = array_shift($data);
foreach($data as $value) {
$result[] = call_user_func_array('array_merge',
array_fill(0, count($result[0]), $value));
}
Get and remove the first element from original
Loop remaining elements and fill result with values X number of values in first element
Since the elements were arrays merge them all into result
If modifying the original is unwanted, then use this method:
$result[] = reset($data);
while($value = next($data)) {
$result[] = call_user_func_array('array_merge',
array_fill(0, count($result[0]), $value));
}
just use array_fill and array_merge functions
$result = array(
$data[0],
array_merge(...array_fill(0,count($data[0]), $data[1])),
array_merge(...array_fill(0,count($data[0])*count($data[0]), $data[2]))
);
print_r($result);
demo on eval.in

Transform numeric array in associative in order to access it from html template

Alright, my data gets stored in a file using the same pattern:
id|title|content
I created a function which explodes the entries by the delimiter '|' into an array.
function get_entries(){
$retAr = array();
$data = file_get_contents("db/entries.log");
$lines = explode("\n", $data); //create array separate by new line
foreach($lines as $line){
$retAr[] = explode('|', $line );
}
return array_reverse( $retAr );
}
Accessable in html:
<?php foreach(get_entries() as $entry): ?>
<a class='title'><?php echo $entry[1];?></a>
<p class='content'><?php echo $entry[2];?></p>
<?php endforeach; ?>
Okay, it works so far but I want to access the data using an associative array pretty much like this.
<?php foreach(transform_to_assoc(get_entries()) as $entry): ?>
<a class='title'><?php echo $entry['title'];?></a>
<p class='content'><?php echo $entry['content'];?></p>
<?php endforeach; ?>
Related function I've written:
function transform_to_assoc($num_array){
$keys = array('id', 'title', 'content');
$assoc = array();
foreach ($num_array as $data) {
foreach ($keys as $key) {
$assoc[$key] = $data;
}
}
return $assoc;
}
Unfortunately, it does not work. Maybe I got something wrong, but I'm sure my approach was the right one. Help would be appreciated.
That should do what you want:
function transform_to_assoc($num_array){
$keys = array('id', 'title', 'content');
$assoc = array();
foreach ($keys as $k=>$key) {
$assoc[$key] = $num_array[$k];
}
return $assoc;
}
Edit:
To use this for a multi dimensional array do the following:
$arr = array(
array(0, 'test heading 1', 'test content 1'),
array(1, 'test heading 1', 'test content 1'),
);
$newArray = array();
foreach($arr as $a) {
$newArray[] = transform_to_assoc($a);
}
function transform_to_assoc($num_array){
$keys = array('id', 'title', 'content');
$assoc = array();
foreach ($keys as $k=>$key) {
$assoc[$key] = $num_array[$k];
}
return $assoc;
}
You could use the list construct. Just exchange the first foreach loop with this:
foreach($lines as $i => $line){
list($retAr[$i]['id'], $retAr[$i]['title'], $retAr[$i]['content']) = explode('|', $line );
}

PHP filter links

i have this array
$array = array(
"http://www.mywebsite.com/eternal_link_1",
"http://www.mywebsite.com/eternal_link_2/",
"http://www.mywebsite.com/eternal_link_1/#",
"http://subdomain1.mywebwite.com",
"http://subdomain2.mywebwite.com/eternal_link",
"http://www.external-link.com"
);
$eternal_links = array();
$subdomain_links = array();
$external_links = array();
how i can filter $array and add the values to the 3 arrays above?
You can use strpos to find the correct string.
foreach($array as $item){
if(strpos($item, 'external') == TRUE){
array_push($external_links, $item);
}
// and go on..
}

Concatenate object items

I have the following function which works fine.
function ($objects, $items = array())
{
$result = array();
foreach ($objects as $object) {
$result[$object->id] = $object->first_name . ' ' . $object->last_name;
}
return $result;
}
However, I would like to pass in an array to $items, and have that exploded, so that I dont have to specify first_name and last_name manually.
If $item was only a single value (and not an array), then it would be simple:
$result[$object->id] = $object->$item;
But I have no idea how to make this work if $items contains multiple values and I want to join them with a space. Something like, the following, but I need to get the $object in there
$items = array('first_name', 'last_name');
$result[$object->id] = implode(' ', $items);
Do I get you right that you`d like to use the strings in $item as property-names of $object?
function ($objects, $items = array())
{
$result = array();
foreach ($objects as $object) {
$valuesToAssign = array();
foreach ($items as $property) {
$valuesToAssign[] = $object->$property;
}
$result[$object->id] = implode(' ', $valuesToAssign);
}
return $result;
}
I have no idea to avoid the second foreach, but that gives you the desired result.
Not sure if I got you right, but how about this:
function foo($objects, $items = array()) {
$result = array();
$keys = array_flip($items);
foreach ($objects as $object) {
// Cast object to array, then omit all the stuff that is not in $items
$values = array_intersect_key((array) $object, $keys);
// Glue the pieces together
$result[$object->id] = implode(' ', $values);
}
return $result;
}
Demo: http://codepad.viper-7.com/l8vmGr

return monodimensional-array from multidimensional

I have a multidimensional array:
$array=array( 0=>array('text'=>'text1','desc'=>'blablabla'),
1=>array('text'=>'text2','desc'=>'blablabla'),
2=>array('text'=>'blablabla','desc'=>'blablabla'));
Is there a function to return a monodimensional array based on the $text values?
Example:
monoarray($array);
//returns: array(0=>'text1',1=>'text2',2=>'blablabla');
Maybe a built-in function?
This will return array with first values in inner arrays:
$ar = array_map('array_shift', $array);
For last values this will do:
$ar = array_map('array_pop', $array);
If you want to take another element from inner array's, you must wrote your own function (PHP 5.3 attitude):
$ar = array_map(function($a) {
return $a[(key you want to return)];
}, $array);
Do it like this:
function GetItOut($multiarray, $FindKey)
{
$result = array();
foreach($multiarray as $MultiKey => $array)
$result[$MultiKey] = $array[$FindKey];
return $result;
}
$Result = GetItOut($multiarray, 'text');
print_r($Result);
Easiest way is to define your own function, with a foreach loop. You could probably use one of the numerous php array functions, but it's probably not worth your time.
The foreach loop would look something like:
function monoarray($myArray) {
$output = array();
foreach($myArray as $key=>$value) {
if( $key == 'text' ) {
$output[] = $value;
}
}
return $output;
}
If the order of your keys never changes (i.e.: text is always the first one), you can use:
$new_array = array_map('current', $array);
Otherwise, you can use:
$new_array = array_map(function($val) {
return $val['text'];
}, $array);
Or:
$new_array = array();
foreach ($array as $val) {
$new_array[] = $val['text'];
}
Try this:
function monoarray($array)
{
$result = array();
if (is_array($array) === true)
{
foreach (new RecursiveIteratorIterator(new RecursiveArrayIterator($array)) as $value)
{
$result[] = $value;
}
}
return $result;
}
With PHP, you only have to use the function print_r();
So --> print_r($array);
Hope that will help you :D

Categories