how to separate array with commas? - php

i have this $_categories as array()
<?php print_r($_categories); ?> is this: Array ( [0] => 13 [1] => 7 )
what i need is to extract de values 13 and 7 into this format: 13,7 (without comma after the last value).
i have this code but is not there yet... the result is: 137 and not 13,7
<?php
if ( is_array($_categories) ) {
foreach ($_categories as $key => $value) {
$out = array();
array_push($out, $value);
echo implode(', ', $out);
}
}
else {
echo '<li>There are no saved values yet.</li>';
}
?>
Thanks, nelson

Directly use
echo implode(', ', $_categories);

Everytime you are implodeing just one element,and echoing just it. Try like this:
$out = array(); //putting outside of the loop
foreach ($_categories as $key => $value) {
array_push($out, $value);
}
echo implode(', ', $out); //putting outside of the loop

Related

Looping into a multidimensional array with PHP

I've got this array:
Array
(
[0] => Array
(
[name] => System
[order] => 1
[icon] => stats.svg
[0] => Array
(
[title] => Multilingual
)
[1] => Array
(
[title] => Coloring
)
[2] => Array
(
[title] => Team work
)
[3] => Array
(
[title] => Tutorials
)
)
)
I want to loop into this to show the section name and after all the features containing in the following array.
So, this is what I made:
foreach ($features as $feature => $info) {
echo '
'.$info['name'].'
<ul class="menu-vertical bullets">
';
foreach (array_values($info) as $i => $key) {
echo '
<li>'.$key['title'].'</li>
';
}
echo '
</ul>
';
}
It works except for the first third <li> where I have the first char of name, order and icon value.
Do you know why ?
Thanks.
array_values return value of array so for info values is name, order, icon, 0, 1, ...
Your values foreach is wrong if you just want print title you can use:
foreach ($features as $feature => $info) {
echo '
'.$info['name'].'
<ul class="menu-vertical bullets">
';
//Remove some keys from info array
$removeKeys = array('name', 'order', 'icon');
$arr = $info;
foreach($removeKeys as $key) {
unset($arr[$key]);
}
foreach (array_values($arr) as $i => $key) {
echo '
<li>'.$key['title'].'</li>
';
}
echo '
</ul>
';
}
In php, array_values means all the values of the array. So array_values($info) is array($info['name'], $info['order'], $info['icon'], $info[0], $info[1], $info[2], $info[3])
in your example, you can skip the non-integer keys of the $info to get your titles:
<?php
$features = array();
$info = array();
$info['name'] = 'System';
$info['order'] = 1;
$info['icon'] = 'stats.svg';
$info[] = array('title'=>'Multilingual');
$info[] = array('title'=>'Coloring');
$features[] = $info;
foreach ($features as $feature => $info) {
echo $info['name'] . PHP_EOL;
echo '<ul class="menu-vertical bullets">' . PHP_EOL;
foreach ($info as $k => $item) {
if(!is_int($k)) continue;
echo '<li>' . $item['title'] . '</li>' . PHP_EOL;
}
echo '</ul>' . PHP_EOL;
}
BUT, your original data structure is not well designed and hard to use. For a better design, you can consider the following code, move your items to a sub array of $info:
<?php
$features = array();
$info = array();
$info['name'] = 'System';
$info['order'] = 1;
$info['icon'] = 'stats.svg';
$info['items'] = array();
$info['items'][] = array('title'=>'Multilingual');
$info['items'][] = array('title'=>'Coloring');
$features[] = $info;
foreach ($features as $feature => $info) {
echo $info['name'] . PHP_EOL;
echo '<ul class="menu-vertical bullets">' . PHP_EOL;
foreach ($info['items'] as $item) {
echo '<li>' . $item['title'] . '</li>' . PHP_EOL;
}
echo '</ul>' . PHP_EOL;
}
Sample output of the two demos:
System
<ul class="menu-vertical bullets">
<li>Multilingual</li>
<li>Coloring</li>
</ul>
It works except for the first third li where I have the first char of name, order and icon value. Do you know why ?
Why you see first chars of the values of 'name', 'order', 'icon'? Let see how PHP works.
Take the first loop as an example: foreach (array_values($info) as $i => $key)
Then $i == 0, $key == 'System'
We know that $key[0] == 'S', $key[1] == 'y', $key[2] == 's', etc.
Then you try to access $key['title'], but the string 'title' is not valid as a string offset, so it is converted to an integer by PHP: intval('title') == 0.
Then $key['title'] == $key[intval('title')] == 'S'
That's what you see.
array_value() returns the values of the array, here you will get the value of the array $info and what I understand is that is not what you need. See details for array_value().
You can check if the key for the $info is an integer. if yes, echo the title. Give this a try.
foreach ($features as $feature => $info) {
echo $info['name'].'<ul class="menu-vertical bullets">';
foreach ($info as $key => $value) {
if (is_int($key)) {
echo '<li>'.$key['title'].'</li>';
}
}
echo '</ul>';
}

How to use array with foreach in PHP

I'm try to using array in PHP by finding it index and keys as foreach.
example I want to get $k["ab"] or $ro["hh"] but I can't get it
<?php
$data = array(
"test"=>array(
"some"=>"d",
"hello"=>"e",
"ther"=>"a"
),
"ab"=>array(
"ad"=>"tt",
"de"=>"jj",
"hh"=>"uu")
);
foreach($data as $k=>$ro){
var_dump($k);
}
?>
You'd better learn the structure of multi-dimensional array.
<?php
$data = array(
"test"=>array(
"some"=>"d",
"hello"=>"e",
"ther"=>"a"
),
"ab"=>array(
"ad"=>"tt",
"de"=>"jj",
"hh"=>"uu")
);
foreach($data as $key => $values){
echo $key; // which will output "test", "ab", which are the array keys
print_r($values); // which will output the contents of the inner array (e.g. array("some"=>"d","hello"=>"e","ther"=>"a") )
// to obtain the inner array values, you can either use another foreach...
foreach($values as $k => $v) {
echo $k . ', ' . $v; // which will output "ad, tt", etc
}
// ...or specify which key to obtain
if(isset($values["ad"])) { echo $values["ad"]; }
// isset() must be used, as the key does not exist in 1st inner array
}
?>
Please try Below :
<?php
$data = array(
"test"=>array(
"some"=>"d",
"hello"=>"e",
"ther"=>"a"
),
"ab"=>array(
"ad"=>"tt",
"de"=>"jj",
"hh"=>"uu")
);
foreach($data as $k=>$ro){
if($k == "ab"){
echo "<pre>";
print_R($ro);
echo 'HH Value ===> '.$ro['hh'];
}
}
?>
And Want to get All values and Keys Try Below For Each :
foreach($data as $k=>$ro){
foreach($ro as $inner_key => $inner_value){
echo "<br/> Key ===> ".$inner_key."==== value =====>".$inner_value;
}
}

exploade accosiative array type data

I have data like following
string(133) "lindsey#testmail.com=>5.jpg,rickey#testmail.com=>6.jpg,darnell#testmail.com=>84.jpg,ball#gmail.com =>49.jpg,norton#tesing.com=>68.jpg"
i want to explode email and image separately.
i use explode but it didn't work.
i also try associative array.
here is my code but it didn't work.
foreach ($array as $key => $value ) {
echo $key;
echo "<li><img src=\"".base_url()."images/menters/".$values."\" class=\"img-border\"/><span>icon</span></li>\n";
}
i think it happen additional string(133)
i have no idea how to accomplish this
You can't do that with a single explode, you have to explode the string twice. You can then use an associative array to store values and use them
$array = explode(',' $string);
foreach ($array as $key => $val) {
$exp = explode('=>', $val);
$assoc_array[$key]['mail'] = $exp[0];
$assoc_array[$key]['img'] = $exp[1];
}
foreach ($assoc_array as $val) {
echo 'Mail : ', $val['mail'], '<br>';
echo 'Image : ', $val['img'];
}

Find last character in multi-dimensional associative array and delete it

I have an associative array in a foreach like this:
foreach ($mArray as $aValue) {
foreach ($aValue as $key => $value) {
echo $html->find($key,$value)
}
}
It gives me this output:
bobby
johnny
Now I would like to get the last character which is y so I did:
echo substr($TheString, -1);
But this gives me: yy because its a multi-dimensional array so it gives me the last characters in each array. What can I do to get the last character on the page y (..and delete it)?
$last_char = '';
foreach ($mArray as $aValue) {
foreach ($aValue as $key => $value) {
if(substr($html->find($key,$value), -1) == 'y'){
$last_char = $html->find($key,$value);
}
}
}
echo $last_char;
This seems to work for me
echo substr_replace($TheString,"",-3);
Try This :
echo substr($TheString, -1, 1);
OR replace a string Removing y
$s="abcdey";
$m=substr($s,0,-1);
echo substr_replace($s,$m,0)
Try This :
$array = array(
"foo" => "jonny",
"bar" => "monny",
);
$i=0;
$con=count($array);
foreach($array as $key => $value)
{
$i++;
if($i==$con)
{
$s=$value;
$m=substr($value,0,-1);
$value=substr_replace($s,$m,0);
echo "Removed Y from array of last item =".$m."</br>";
}
echo $value."</br>";
}

How to echo out the values of this array?

How to echo out the values individually of this array?
Array ( [0] => 20120514 [1] => My Event 3 )
so
echo $value[0]; etc
I have this so far:
foreach (json_decode($json_data_string, true) as $item) {
$eventDate = trim($item['date']);
// positive limit
$myarray = (explode(',', $eventDate, 2));
foreach ($myarray as $value) {
echo $value;
}
This echo's out the whole string no as an array. and if i do this?
echo $value[0};
Then I only get 2 characters of it??
The print_r :
Array ( [0] => 20120430 [1] => My Event 1 )
foreach ($array as $key => $val) {
echo $val;
}
Here is a simple routine for an array of primitive elements:
for ($i = 0; $i < count($mySimpleArray); $i++)
{
echo $mySimpleArray[$i] . "\n";
}
you need the set key and value in foreach loop for that:
foreach($item AS $key -> $value) {
echo $value;
}
this should do the trick :)
The problem here is in your explode statement
//$item['date'] presumably = 20120514. Do a print of this
$eventDate = trim($item['date']);
//This explodes on , but there is no , in $eventDate
//You also have a limit of 2 set in the below explode statement
$myarray = (explode(',', $eventDate, 2));
//$myarray is currently = to '20'
foreach ($myarray as $value) {
//Now you are iterating through a string
echo $value;
}
Try changing your initial $item['date'] to be 2012,04,30 if that's what you're trying to do. Otherwise I'm not entirely sure what you're trying to print.
var_dump($value)
it solved my problem, hope yours too.

Categories