I have String array like below format
Array(
"Courses",
"Courses/PHP",
"Courses/PHP/Array",
"Courses/PHP/Functions",
"Courses/JAVA",
"Courses/JAVA/String");
I need result like below
Courses
- PHP
- Array
- Functions
- JAVA
- Strings
I used substr option to get result.
for($i=0;$i<count($outArray);$i++)
{
$strp = strrpos($outArray[$i], '/')+1;
$result[] = substr($outArray[$i], $strp);
}
But I didn't get result like tree structure.
How do I get result like tree structure.
Something like that?
$a = array(
"Courses",
"Courses/PHP",
"Courses/PHP/Array",
"Courses/PHP/Functions",
"Courses/JAVA",
"Courses/JAVA/String");
$result = array();
foreach($a as $item){
$itemparts = explode("/", $item);
$last = &$result;
for($i=0; $i < count($itemparts); $i++){
$part = $itemparts[$i];
if($i+1 < count($itemparts))
$last = &$last[$part];
else
$last[$part] = array();
}
}
var_dump($result);
The result is:
array(1) {
["Courses"]=>
array(2) {
["PHP"]=>
array(2) {
["Array"]=>
array(0) {
}
["Functions"]=>
array(0) {
}
}
["JAVA"]=>
&array(1) {
["String"]=>
array(0) {
}
}
}
}
How about this one:
<?php
$outArray = Array(
"Courses",
"Courses/PHP",
"Courses/PHP/Array",
"Courses/PHP/Functions",
"Courses/JAVA",
"Courses/JAVA/String");
echo "-" . $outArray[0] . "<br/>";
for($i=0;$i<count($outArray) - 1;$i++)
{
create_tree($outArray[$i],$outArray[$i+1]);
}
function create_tree($prev, $arr)
{
$path1 = explode("/", $prev);
$path2 = explode("/", $arr);
if (count($path1) > count($path2))
echo str_repeat(" ",count($path1) - 1) . "-" . end($path2);
else
echo str_repeat(" ",count($path2) - 1) . "-" . end($path2);
echo $outArray[$i] . "<br/>";
}
Outputs:
-Courses
-PHP
-Array
-Functions
-JAVA
-Strings
Related
I have some array that look like this
$links =array('proizvodi','pokloni', 'kuhinja');
I need to create another array that will look like this
$linksNew =array('proizvodi/','proizvodi/pokloni/', 'proizvodi/pokloni/kuhinja/');
Txanks in advance
This would be a primitive approach:
<?php
$input = ['proizvodi','pokloni', 'kuhinja'];
$output = [];
$previous = '';
foreach ($input as $entry) {
$output[] = $previous . $entry . '/';
$previous = end($output);
}
var_dump($output);
This is a version some might consider a bit more elegant:
<?php
$input = ['proizvodi','pokloni', 'kuhinja'];
$output = [];
$previous = '';
array_walk($input, function($entry) use (&$previous, &$output) {
$output[] = $previous . $entry . '/';
$previous = end($output);
});
var_dump($output);
The output of both versions obviously is:
array(3) {
[0]=>
string(10) "proizvodi/"
[1]=>
string(18) "proizvodi/pokloni/"
[2]=>
string(26) "proizvodi/pokloni/kuhinja/"
}
This would be a approach without a for or foreach loop
$links = array('proizvodi','pokloni', 'kuhinja');
$newLinks = array_map(function($i) use ($links) {
return implode(array_slice($links, 0, $i), '/') . '/';
}, range(1, count($links)));
Trying to think of a slicker way, but this works:
for($i=0; $i<count($links); $i++) {
$linksNew[] = implode('/', array_slice($links, $i)) . '/';
}
$linksNew = array_reverse($linksNew);
I have an array like this :
array(3) {
[0]=>
array(2) {
[0]=>
string(6) "action"
[1]=>
string(5) "depot"
}
[1]=>
array(2) {
[0]=>
string(9) "Demandeur"
[1]=>
string(11) "Particulier"
}
[2]=>
array(2) {
[0]=>
string(3) "Nom"
[1]=>
string(6) "Cheval"
}
But I want an associative array, to access it like this : $_REQUEST['Nom'] and have in return 'Cheval' etc...
The first array is actually an object, created with jQuery and here is his construction :
jQuery('input:submit').click(function() {
var itemMetaArray = {};
jQuery('.frm_pro_form :input:not(:hidden, :submit)').each(function() {
if(jQuery('#field_demande').val() != undefined){
itemMetaArray['action'] = jQuery('#field_demande').val();
}
else itemMetaArray['action'] = jQuery('#field_demande2').val();
var label = jQuery(this).closest('.frm_form_field').find('.frm_primary_label').text().trim();
if(jQuery(this).attr('name').indexOf("file") == -1 ) {
itemMetaArray[label] = jQuery(this).val();
}else{
var fileName = jQuery(this).attr('name');
fileName = fileName.substring(0,fileName.length-2);
itemMetaArray[label] = fileName;
}
});
After this, I do some parsing in PHP :
$dataInfo = explode(",",$_POST['dataInfo']);
for ($i = 0; $i < count($dataInfo); ++$i){
$tmpWithoutBrackets[$i] = trim($dataInfo[$i],"{..}");
$tmpWithoutColon[$i] = explode(":",$tmpWithoutBrackets[$i]);
for($j = 0; $j < (count($tmpWithoutColon) + 1); ++$j){
$arrayFinal[$i][$j] = trim($tmpWithoutColon[$i][$j],"\"");
}
$arrayFinal[$i] = array_diff($arrayFinal[$i],array(""));
}
$arrayFinal is the same array as arrayInfo
Thanks in advance for your help
You need to modify your array like this:
$test = array('arrayInfo' => array(array('Nom','Cheval'),array('Prenom','Nathan'),array('Adresse postale','4 impasse Molinas')),'arrayFile' => array(array ('application/pdf','3a514fdbd3ca2af35bf8e5b9c3c80d17','JVBERi0xLjUNCiW1tbW1DQoxIDAgb2JqDQo8PC9UeXBlL0NhdGFsb2cvUGFnZXMgMiAwIFIvTGFuZyhmci1GUikgL1N0cnVjdFRyZWVSb290IDI2IDAgUi9NYXJrSW5mbzw8L01hcmtlZCB0cnVlPj4vTWV0')));
$result = array();
foreach($test as $k=>$t){
$count = 0;
$_key = '';
$_value = '';
foreach($t as $f){
foreach($f as $final){
$count++;
if($count%2!==0){
$_key = $final;
}
else{
$_value = $final;
}
if($_value!==''){
$result[$k][$_key] = $_value;
$_value = '';
}
}
}
}
echo $result['arrayInfo']['Nom'];//Cheval
For your modified question, answer will be a little changed ofcourse:
$test = array(array('Nom','Cheval'),array('Prenom','Nathan'),array('Adresse postale','4 impasse Molinas'));
$result = array();
foreach($test as $k=>$t){
$count = 0;
$_key = '';
$_value = '';
foreach($t as $final){
$count++;
if($count%2!==0){
$_key = $final;
}
else{
$_value = $final;
}
if($_value!==''){
$result[$_key] = $_value;
$_value = '';
}
}
}
var_dump($result);
echo $result['Nom'];//Cheval
I hope it helps
I would like to concatenate each element of array to next one. I want the output array to be:
Array
(
[0] => test
[1] => test/test2
[2] => test/test2/test3
[3] => test/test2/test3/test4
)
I tried the following way which concatenates each string to itself:
$url = preg_split("/[\s\/]+/", "test/test2/test3/test4");
foreach ($url as $dir) {
$dir .= $dir;
}
Any help appreciated.
Maybe another way
<?php
$data = array( 'test', 'test2', 'test3', 'test4' );
for( $i = 0; $i < count( $data ); $i++ )
{
if( $i != 0 )
{
$new[ $i ] = $new[ $i - 1 ] .'/'. $data[ $i ];
}
else
{
$new[ $i ] = $data[ $i ];
}
}
var_dump( $new );
Output
array(4) {
[0]=>
string(4) "test"
[1]=>
string(10) "test/test2"
[2]=>
string(16) "test/test2/test3"
[3]=>
string(22) "test/test2/test3/test4"
}
You should obtain the result you need in $my_array
$url = explode("/", "test/test2/test3/test4");
$str ='';
foreach($url as $key => $value){
if ( $str == '') {
$str .= $str;
} else {
$str .= '/'.$str;
}
$my_array[$key] = $str ;
echo $str . '<br />';
}
var_dump($my_array);
$url = preg_split("/[\s\/]+/", "test/test2/test3/test4");
$arr = array();
$str = '';
foreach ($url as $key => $dir) {
if ($key !== 0) {
$str .= '/' . $dir;
} else {
$str .= $dir;
}
$arr[] = $str;
}
On each iteration concate a string with new value and add it as a separate value for your output array.
Here's a quick way. For simple splitting just use explode():
$url = explode("/", "test/test2/test3/test4");
foreach($url as $value) {
$temp[] = $value;
$result[] = implode("/", $temp);
}
Each time through the loop, add the current value to a temporary array and implode it into the next element of the result.
I' am creating a hierarchical menu using MySQL Database. I' am currently stuck at this point where I' am not able to convert the multidimensional array into a string.
The Outcome
/media/photo-gallery/Title-1
Var Dump of the array
array(2) {
[0]=>
array(2) {
[0]=>
array(1) {
[1]=>
string(5) "media"
}
[1]=>
string(13) "photo-gallery"
}
[1]=>
string(7) "Title-1"
}
I have tried using Implode function, this is what I get
$path = implode("/", $path);
string(19) "Array/photo-gallery"
Get the parent slug from database
function get_path( $page_id ) {
global $db;
$sql = "SELECT * FROM pages WHERE page_id = $page_id";
$query = $db->SELECT($sql);
$rows = $db->FETCH_OBJECT();
$path = array();
foreach( $rows as $row ){
$page_id = $row->page_id;
$page_parent = $row->page_parent;
$page_slug = $row->page_slug;
$path[] = $page_slug;
$path[] = get_path( $page_parent );
$path = array_reverse( $path );
$path = array_filter( $path );
}
return $path;
}
Displays the HTML Menu
function display_children( $parent = "0", $level = "0" ){
global $db;
echo "<ul>";
// retrieve all children of $parent
$sql = "SELECT * FROM pages WHERE page_parent = $parent";
$query = $db->SELECT($sql);
$rows = $db->FETCH_OBJECT();
foreach( $rows as $row ){
$page_id = $row->page_id;
$page_parent = $row->page_parent;
$page_title = $row->page_title;
$page_slug = $row->page_slug;
$path = get_path($page_parent);
$path = array_unique(array_values($path));
var_dump($path);
echo "<li>";
echo "<a href=\"\">";
echo "$page_title | Parent ID: $page_parent";
echo "</li>";
echo "</a>";
// child's children
display_children($page_id, $level + 1);
}
echo "</ul>";
}
looks like your input array is in reverse order, the topmost item goes to the end and the last leaf is the first item. Here is a small function which you can try.
$path = array(array(array('media'),'photo-gallery'),'Title-1');
var_dump($path);
$path = implode('/',sanitizePath($path));
echo $path;
function sanitizePath($pathArray, $initialPath=array()){
foreach($pathArray as $a){
if(is_array($a)){
$initialPath=sanitizePath($a,$initialPath);
}else{
array_push($initialPath,$a);
}
}
return $initialPath;
}
Try this
$array = array(
0 =>array(
0 => array("media","photo-gallery"),
),
1 => "Title-1"
);
$new_array = array();
foreach($array as $k1=>$v1){
if(is_array($v1)){
$new_array = parseArray($new_array, $k1, $v1);
}else{
$new_array = array_merge($new_array, array($k1=>$v1));
}
}
function parseArray($new_array, $key, $val){
if(is_array($val)){
foreach($val as $k2=>$v2){
if(is_array($v2)){
$new_array = parseArray($new_array, $k2, $v2);
}else{
$new_array = array_merge($new_array, array($k2=>$v2));
}
}
}else{
$new_array = array_merge($new_array, array($key=>$val));
}
return $new_array;
}
echo implode('/', $new_array);
Output:
media/photo-gallery/Title-1
With Standard PHP Library (SPL) you can get the desired output
<?php
$array = array(
0 =>array(
0 => array("media","photo-gallery"),
),
1 => "Title-1"
);
$op = new RecursiveIteratorIterator(new RecursiveArrayIterator($array));
foreach($op as $each) {
$result .= '/'.$each;
}
echo $result;.
Output:
/media/photo-gallery/Title-1
I have the result below of 2 arrays starting with [0] what I am wanting to do is return a result of "2" - As I have 2 "strings". How would I do this?
Result:
Array(1) {
[0]=> string(32) "b5cfec3e70d0d57ea848d5d8b9f14d61"
}
Array(1) {
[0]=> string(32) "eda80a3d5b344bc40f3bc04f65b7a357"
}
PHP:
foreach($cart_contents as $key => $row) {
if(in_array($key, $skip))
continue;
$cartData = $row['rowid'];
$cartDataArray = explode(" ", $cartData);
$result = $cartDataArray;
var_dump($result);
}
If I got this right, I think this is what you want:
$count = 0;
foreach($cart_contents as $key => $row) {
if(in_array($key, $skip))
continue;
$cartData = $row['rowid'];
$result = count(explode(" ", $cartData));
$count += $result;
}
var_dump($count);