I tried to split the characters from the available string, but have not found the right way.
I have a string like below :
$tara = 'wordpress/corporate/business';
$k = explode('/', $tara);
foreach ($k as $l) {
var_dump(substr_replace($tara, '', $i, count($l)));
}
The result I want is :
'wordpress',
'wordpress/corporate',
'wordpress/corporate/business'
You could concatenate in every iteration like :
$tara = 'wordpress/corporate/business';
$k = explode('/', $tara);
$result = "";
foreach ($k as $l) {
$result .= '/'.$l;
echo $result."<br>";
}
The output will be :
/wordpress
/wordpress/corporate
/wordpress/corporate/business
If you don't need the slashes at the start you could add a condition like :
$tara = 'wordpress/corporate/business';
$k = explode('/', $tara);
$result = "";
foreach ($k as $l)
{
if( empty($result) ){
echo $l."<br>";
$result = $l;
}else{
$result .= '/'.$l;
echo $result."<br>";
}
}
Or using the shortened version inside loop with ternary operation, like :
foreach ($k as $l)
{
$result .= empty($result) ? $l : '/'.$l;
echo $result."<br>";
}
The output will be :
wordpress
wordpress/corporate
wordpress/corporate/business
How about constructing the results from the array alements:
$tara = 'wordpress/corporate/business';
$k = explode('/', $tara);
$s = '';
foreach ($k as $l) {
$s .= ($s != '' ? '/' : '') . $l;
var_dump($s);
}
This results in:
string(9) "wordpress"
string(19) "wordpress/corporate"
string(28) "wordpress/corporate/business"
You should explode your string array and print in foreach all exploded values using implode and temporary array(for example). Here is working code:
$tara = 'wordpress/corporate/business';
$k = explode('/', $tara);
$tmp = [];
foreach ($k as $l) {
$tmp[] .= $l;
var_dump(implode($tmp, '/'));
}
Create new array and inside foreach
<?php
$tara = 'wordpress/corporate/business';
$url = array();
foreach(explode("/",$tara) as $val){
$url[] = $val;
echo implode("/",$url)."\n";
}
?>
Demo : https://eval.in/932527
Output is
wordpress
wordpress/corporate
wordpress/corporate/business
Try This, Its Easiest :
$tara = 'wordpress/corporate/business';
$k = explode('/', $tara);
$str = array();
foreach ($k as $l) {
$str[] = $l;
echo implode('/',$str)."<br>";
}
Related
$arr = ['Governance->Policies->Prescriptions->CAS Alerts',
'Users->User Departments->Department Hierarchy',
'Settings->Registrar->Finance',
'Logs->Second Opinion Log'];
This is array and I want to convert it into string like below
The string should be one it just concate in one string.
Governance->Policies
Governance->Prescriptions
Governance->CAS Alerts
Users->User Departments
Users->Department Hierarchy
Settings->Registrar
Settings->Finance
Logs->Second Opinion Log
$arr = ['Governance->Policies->Prescriptions->CAS Alerts',
'Users->User Departments->Department Hierarchy',
'Settings->Registrar->Finance',
'Logs->Second Opinion Log'];
$temp = '';
for($i = 0; $i < count($arr); $i++){
$arrVal = [];
$arrVal = explode('->',$arr[$i]);
if(count($arrVal) > 1){
for($j=0; $j < count($arrVal); $j++){
if($j == 0){
$temp .= $arrVal[$j];
}else{
$temp .='->'.$arrVal[$j]."\n";
if($j == count($arrVal) - 1){
$temp .= "\n";
}else{
$temp .= substr($temp, 0, strpos($temp, "->"));
}
}
}
}
}
echo $temp;
As you iterate your array of arrow-delimited strings, explode each element on its arrows, separate the the first value from the rest, then iterate the remaining elements from the explosion and prepend the cached, first value and push into the result array.
Code: (Demo)
$result = [];
foreach ($arr as $string) {
$parts = explode('->', $string);
$parent = array_shift($parts);
foreach ($parts as $child) {
$result[] = "{$parent}->$child";
}
}
var_export($result);
Here the solution:
<?php
//This might help full
$arr = ['Governance->Policies->Prescriptions->CAS Alerts',
'Users->User Departments->Department Hierarchy',
'Settings->Registrar->Finance',
'Logs->Second Opinion Log'];
$result="";
$newline="<br>";
foreach($arr as $data){
$wordlist=explode('->',$data);
$firstword=$wordlist[0];
$temp='';
foreach($wordlist as $key=>$value){
if($key > 0){
$temp.=$firstword."->".$value.$newline;
}
}
$temp.=$newline;
$result.=$temp;
}
echo $result;
?>
Output :
Governance->Policies
Governance->Prescriptions
Governance->CAS Alerts
Users->User Departments
Users->Department Hierarchy
Settings->Registrar
Settings->Finance
Logs->Second Opinion Log
$arr = ['Governance->Policies->Prescriptions->CAS Alerts',
'Users->User Departments->Department Hierarchy',
'Settings->Registrar->Finance',
'Logs->Second Opinion Log'];
foreach ($arr as $path) {
$path_elements = explode('->', $path);
if (count($path_elements) > 1) {
$path_head = $path_elements[0];
$path_tail = array_slice($path_elements, 1);
foreach ($path_tail as $path_item) {
echo $path_head, '->', $path_item, "<br>";
}
echo "<br>";
}
}
Demo : https://onlinephp.io/c/9eb2d
Or, using JOIN()
$arr = ['Governance->Policies->Prescriptions->CAS Alerts',
'Users->User Departments->Department Hierarchy',
'Settings->Registrar->Finance',
'Logs->Second Opinion Log'];
foreach ($arr as $path) {
$path_elements = explode('->', $path);
if (count($path_elements) > 1) {
$path_head = $path_elements[0];
$path_tail = array_slice($path_elements, 1);
echo
$path_head,
'->',
join('<br>'. $path_head.'->',$path_tail),
'<br><br>';
}
}
Demo : https://onlinephp.io/c/c1826
I have a string like
$totalValues ="4565:4,4566:5,4567:6";
Now i want only values after ':' with coma separated ,i.e i want string like $SubValues = "4,5,6"
Thanks
using array_map, implode and explode
$totalValues ="4565:4,4566:5,4567:6";
echo implode(',',array_map(function($val){
$val = explode(':',$val);
return $val[1];
},explode(',',$totalValues)));
try this code it is working
<?php
$str="4565:4,4566:5,4567:6";;
$data =explode(",", $str);
echo '<pre>';
print_r($data);
$newstring="";
foreach ($data as $key => $value) {
preg_match('/:(.*)/',$value,$matches);
$newstring.=$matches[1].",";
}
echo rtrim($newstring,",");
Output
i have updated my code please check it
<?php
$str="4565:4,4566:5,4567:6";
$data1=explode(",", $str);
$newstring1="";
foreach ($data1 as $key1 => $value) {
preg_match('/(.*?):/',$value,$matches);
$newstring1.=$matches[1].",";
}
echo rtrim($newstring1,",");
you might want it this way:
$totalValues ="4565:4,4566:5,4567:6";
$temp = explode(':', $totalValues);
$subValues = $temp[1][0];
$x = count($temp);
for ($i = 2; $i < $x; $i++) {
$subValues .= ',' . $temp[$i][0];
}
echo $subValues;
I have a comma separated string like
$str = "word1,word2,word3";
And i want to make a parent child relationship array from it.
Here is an example:
Try this simply making own function as
$str = "word1,word2,word3";
$res = [];
function makeNested($arr) {
if(count($arr)<2)
return $arr;
$key = array_shift($arr);
return array($key => makeNested($arr));
}
print_r(makeNested(explode(',', $str)));
Demo
function tooLazyToCode($string)
{
$structure = null;
foreach (array_reverse(explode(',', $string)) as $part) {
$structure = ($structure == null) ? $part : array($part => $structure);
}
return $structure;
}
Please check below code it will take half of the time of the above answers:
<?php
$str = "sports,cricket,football,hockey,tennis";
$arr = explode(',', $str);
$result = array();
$arr_len = count($arr) - 1;
$prev = $arr_len;
for($i = $arr_len; $i>=0;$i--){
if($prev != $i){
$result = array($arr[$i] => $result);
} else {
$result = array ($arr[$i]);
}
$prev = $i;
}
echo '<pre>',print_r($result),'</pre>';
Here is another code for you, it will give you result as you have asked :
<?php
$str = "sports,cricket,football,hockey,tennis";
$arr = explode(',', $str);
$result = array();
$arr_len = count($arr) - 1;
$prev = $arr_len;
for($i = $arr_len; $i>=0;$i--){
if($prev != $i){
if($i == 0){
$result = array($arr[$i] => $result);
}else{
$result = array(array($arr[$i] => $result));
}
} else {
$result = array ($arr[$i]);
}
$prev = $i;
}
echo '<pre>',print_r($result),'</pre>';
I am trying to display a number that has the english comma separation.
This code gets the number of likes from multiple pages and displays them in a list ordered by number of facebook likes.
function array_sort($array, $on, $order=SORT_ASC)
{
$new_array = array();
$sortable_array = array();
if (count($array) > 0) {
foreach ($array as $k => $v) {
if (is_array($v)) {
foreach ($v as $k2 => $v2) {
if ($k2 == $on) {
$sortable_array[$k] = $v2;
}
}
} else {
$sortable_array[$k] = $v;
}
}
switch ($order) {
case SORT_ASC:
asort($sortable_array);
break;
case SORT_DESC:
arsort($sortable_array);
break;
}
foreach ($sortable_array as $k => $v) {
$new_array[$k] = $array[$k];
}
}
return $new_array;
}
function getLikes($arr){
$urls = "";
// Add urls to check for likes
for($i = 0;$i < count($arr);$i++) {
if($urls != "") $urls .= ",";
$urls .= $arr[$i];
}
// Retreive info from Facebook
$xml = simplexml_load_file("http://api.facebook.com/restserver.php?method=links.getStats&urls=" . $urls);
$likes = array();
// Loop through the result and populate an array with the likes
for ($i = 0;$i < count($arr);$i++) {
$url = $xml->link_stat[$i]->url;
$counts = (int)$xml->link_stat[$i]->like_count;
$likes[] = array('likes' => $counts,'url' => $url);
}
return $likes;
}
$array = array("URL HERE","URL HERE");
$likes = getLikes($array);
$likes = array_sort($likes, 'likes', SORT_DESC);
$english_format_number = number_format($likes, 'likes');
foreach ($likes as $key => $val) {
echo "<li class='facebook'><div class='fb-page'><div class='rank'>" . $key . "</div>" . "<div class='thumb " . $val['url'] . "'><div class='link'>" . $val['url'] . "</div></div>" . "<div class='likes'>" . $val['likes'] . "</div></div></li><br />";
}
The code works fine, by the way I am not a coder, and am only just getting into it.
I was trying to add in something like
$english_format_number = number_format($likes, 'likes');
But of course I have no idea if I can do that or where to put it.
Can anyone help?
you use wrong parameter in number_format function. the correct format is number_format(number,decimals,decimalpoint,separator). so change you code to
$english_format_number = number_format($likes, 0, ',', '.') . 'likes';
I need to build an tree (with arrays) from given urls.
I have the following list of urls:
http://domain.com/a/a.jsp
http://domain.com/a/b/a.jsp
http://domain.com/a/b/b.jsp
http://domain.com/a/b/c.jsp
http://domain.com/a/c/1.jsp
http://domain.com/a/d/2.jsp
http://domain.com/a/d/a/2.jsp
now i need an array like this:
domain.com
a
a.jsp
b
a.jsp
b.jsp
c.jsp
c
1.jsp
d
2.jsp
a
2.jsp
How can i do this with php?
i thought mark's solution was a bit complicated so here's my take on it:
(note: when you get to the filename part of the URI, I set it as both the key and the value, wasn't sure what was expected there, the nested sample didn't give much insight.)
<?php
$urls = array(
'http://domain.com/a/a.jsp',
'http://domain.com/a/b/a.jsp',
'http://domain.com/a/b/b.jsp',
'http://domain.com/a/b/c.jsp',
'http://domain.com/a/c/1.jsp',
'http://domain.com/a/d/2.jsp',
'http://domain.com/a/d/a/2.jsp'
);
$array = array();
foreach ($urls as $url)
{
$url = str_replace('http://', '', $url);
$parts = explode('/', $url);
krsort($parts);
$line_array = null;
$part_count = count($parts);
foreach ($parts as $key => $value)
{
if ($line_array == null)
{
$line_array = array($value => $value);
}
else
{
$temp_array = $line_array;
$line_array = array($value => $temp_array);
}
}
$array = array_merge_recursive($array, $line_array);
}
print_r($array);
?>
$urlArray = array( 'http://domain.com/a/a.jsp',
'http://domain.com/a/b/a.jsp',
'http://domain.com/a/b/b.jsp',
'http://domain.com/a/b/c.jsp',
'http://domain.com/a/c/1.jsp',
'http://domain.com/a/d/2.jsp',
'http://domain.com/a/d/a/2.jsp'
);
function testMapping($tree,$level,$value) {
foreach($tree['value'] as $k => $val) {
if (($val == $value) && ($tree['level'][$k] == $level)) {
return true;
}
}
return false;
}
$tree = array();
$i = 0;
foreach($urlArray as $url) {
$parsed = parse_url($url);
if ((!isset($tree['value'])) || (!in_array($parsed['host'],$tree['value']))) {
$tree['value'][$i] = $parsed['host'];
$tree['level'][$i++] = 0;
}
$path = explode('/',$parsed['path']);
array_shift($path);
$level = 1;
foreach($path as $k => $node) {
if (!testMapping($tree,$k+1,$node)) {
$tree['value'][$i] = $node;
$tree['level'][$i++] = $level;
}
$level++;
}
}
echo '<pre>';
for ($i = 0; $i < count($tree['value']); $i++) {
echo str_repeat(' ',$tree['level'][$i]*2);
echo $tree['value'][$i];
echo '<br />';
}
echo '</pre>';