Solved

HELP re-arrange an array into 2 kinds of array

Posted on 2013-11-18
9
340 Views
Last Modified: 2013-11-18
Hi all,
I have this array:
Array
(
    [0] => "**MAIN ITEM**"
    [1] => "*Self Defense*"
    [2] => "Pepper Spray|50|"
    [3] => "Stun Gun|75|"
    [4] => "A Hammer|20|"
    [5] => "*Sports*"
    [6] => "Baseball Cap|22|"
    [7] => "DuoGolf Stick|175|"
    [8] => "Portable Pool|1165|"
    [9] => "**ADDITIONAL ITEM**"
    [10] => "*Food & Drinks*"
    [11] => "Sprite|11|"
    [12] => "7 Up|10|"
    [13] => "Coca Cola|9|"
    [14] => "**MISC ITEM**"
    [15] => "*Kids*"
    [16] => "Pair of Baloons|2|"
    [17] => "Rubber Car Toy|11|"
    [18] => "China Toy|15|"
)

Open in new window


Can you help me re-arrange above array into this:
Array
(
    [0] => "MAIN ITEM|Self Defense|Pepper Spray|50|"
    [1] => "MAIN ITEM|Self Defense|Stun Gun|75|"
    [2] => "MAIN ITEM|Self Defense|A Hammer|20|"
    [3] => "MAIN ITEM|Sports|Baseball Cap|22|"
    [4] => "MAIN ITEM|Sports|DuoGolf Stick|175|"
    [5] => "MAIN ITEM|Sports|Portable Pool|1165|"
    [6] => "ADDITIONAL ITEM|Food & Drinks|Sprite|11|"
    [7] => "ADDITIONAL ITEM|Food & Drinks|7 Up|10|"
    [8] => "ADDITIONAL ITEM|Food & Drinks|Coca Cola|9|"
    [9] => "MISC ITEM|Kids|Pair of Baloons|2|"
    [10] => "MISC ITEM|Kids|Rubber Car Toy|11|"
    [11] => "MISC ITEM|Kids|China Toy|15|"
)

Open in new window


And also into a multidimensional array like this:
Array
(
    [MAIN ITEM] => array (
	[Self Defense] => array (
		[0] => "Pepper Spray|50|",
		[1] => "Stun Gun|75|",
		[2] => "A Hammer|20|"
	),
	[Sports] => array (
		[0] => "Baseball Cap|22|",
		[1] => "DuoGolf Stick|175|",
		[2] => "Portable Pool|1165|"
	)
    ),
    [ADDITIONAL ITEM] => array (
	[Food & Drinks] => array (
		[0] => "Sprite|11|",
		[1] => "7 Up|10|",
		[2] => "Coca Cola|9|"
	)
    ),
    [MISC ITEM] => array (
	[Kids] => array (
		[0] => "Pair of Baloons|2|",
		[1] => "Rubber Car Toy|11|",
		[2] => "China Toy|15|"
	)
    )
)

Open in new window


Basically I'm just learning into arrays and would like to know how to convert/re-arrange the first one into 2 kinds of arrays.
I've been playing around with foreach, preg_match, substr, but seems that I cant find a way to split and re-array it :(
Please help me ... Thanks.
0
Comment
Question by:tobece
  • 5
  • 2
  • 2
9 Comments
 
LVL 109

Expert Comment

by:Ray Paseur
ID: 39656170
For a collection of good learning resources, for anyone starting PHP, these two articles will be helpful.  Have a read, and while you do that I'll try to set up some code examples.

http://www.experts-exchange.com/Web_Development/Web_Languages-Standards/PHP/A_11769-And-by-the-way-I-am-new-to-PHP.html

http://www.experts-exchange.com/Web_Development/Web_Languages-Standards/PHP/A_12293-AntiPHPatterns-and-AntiPHPractices.html
0
 
LVL 109

Expert Comment

by:Ray Paseur
ID: 39656186
Here's the first example.

<?php // RAY_temp_tobece.php
error_reporting(E_ALL);
echo '<pre>';

// STARTING TEST DATA SET
$arr = Array
(
      0 => "**MAIN ITEM**"
   ,  1 => "*Self Defense*"
   ,  2 => "Pepper Spray|50|"
   ,  3 => "Stun Gun|75|"
   ,  4 => "A Hammer|20|"
   ,  5 => "*Sports*"
   ,  6 => "Baseball Cap|22|"
   ,  7 => "DuoGolf Stick|175|"
   ,  8 => "Portable Pool|1165|"
   ,  9 => "**ADDITIONAL ITEM**"
   , 10 => "*Food & Drinks*"
   , 11 => "Sprite|11|"
   , 12 => "7 Up|10|"
   , 13 => "Coca Cola|9|"
   , 14 => "**MISC ITEM**"
   , 15 => "*Kids*"
   , 16 => "Pair of Baloons|2|"
   , 17 => "Rubber Car Toy|11|"
   , 18 => "China Toy|15|"
)
;

// DOES IT LOOK RIGHT?
print_r($arr);

// DOUBLE STAR IS FIRST CATEGORY, SINGLE STAR IS SECOND CATEGORY, NO STAR IS LIST ITEM
$out = array();
foreach ($arr as $str)
{
    if (substr($str,0,2) == '**')
    {
        $first = $str;
    }
    elseif (substr($str,0,1) == '*')
    {
        $second = $str;
    }
    else
    {
        $out[]
        = str_replace('*', NULL, $first)
        . '|'
        . str_replace('*', NULL, $second)
        . '|'
        . $str;
    }
}
// DOES IT LOOK RIGHT
print_r($out);

Open in new window

0
 
LVL 13

Assisted Solution

by:duncanb7
duncanb7 earned 50 total points
ID: 39656200
Dear  tobece,

the following code is working for your first request completely and I tried and it works

for multidimensional array, I think you can handle based on the following code

Hope it will help

<?php
$arr=Array
(
     "**MAIN ITEM**",
    "*Self Defense*",
    "Pepper Spray|50|",
    "Stun Gun|75|",
     "A Hammer|20|",
    "*Sports*",
    "Baseball Cap|22|",
    "DuoGolf Stick|175|",
    "Portable Pool|1165|",
     "**ADDITIONAL ITEM**",
     "*Food & Drinks*",
     "Sprite|11|",
     "7 Up|10|",
     "Coca Cola|9|",
     "**MISC ITEM**",
    "*Kids*",
    "Pair of Baloons|2|",
    "Rubber Car Toy|11|",
    "China Toy|15|"
);

$cnt=count($arr); $mline=array();$i=0;
for( $a=0;$a<$cnt;$a++){if( stripos("#".$arr[$a],"**")>0){$mline[$i]=$arr[$a]; $i=$i+1;}}
$kline=array();$jline=array();$i=0;$j=0;$k=0;
for( $a=0;$a<$cnt;$a++){
if (@stripos("#".$arr[$a+1],"**")>0)$i=$i+1;
if( stripos("#".$arr[$a],"*")>0 && stripos("#".$arr[$a],"**")==false){$kline[$j]=$arr[$a];
for( $b=0;$b<$cnt;$b++){if($arr[$b]==$kline[$j]){break;}}
for( $c=$b+1;$c<$cnt;$c++){
if(stripos("#".$arr[$c],"*")>0) break;
$jinal[$k]=$mline[$i]."|".$kline[$j]."|".$arr[$c];$jline[$k]=str_replace("*","",$jinal[$k]);$k=$k+1;
}
$j=$j+1;
}}
print_r($jline);
?>

Open in new window

0
Master Your Team's Linux and Cloud Stack

Come see why top tech companies like Mailchimp and Media Temple use Linux Academy to build their employee training programs.

 
LVL 109

Expert Comment

by:Ray Paseur
ID: 39656257
Here is the second example.  It starts on line 60.

<?php // RAY_temp_tobece.php
error_reporting(E_ALL);
echo '<pre>';

// STARTING TEST DATA SET
$arr = Array
(
      0 => "**MAIN ITEM**"
   ,  1 => "*Self Defense*"
   ,  2 => "Pepper Spray|50|"
   ,  3 => "Stun Gun|75|"
   ,  4 => "A Hammer|20|"
   ,  5 => "*Sports*"
   ,  6 => "Baseball Cap|22|"
   ,  7 => "DuoGolf Stick|175|"
   ,  8 => "Portable Pool|1165|"
   ,  9 => "**ADDITIONAL ITEM**"
   , 10 => "*Food & Drinks*"
   , 11 => "Sprite|11|"
   , 12 => "7 Up|10|"
   , 13 => "Coca Cola|9|"
   , 14 => "**MISC ITEM**"
   , 15 => "*Kids*"
   , 16 => "Pair of Baloons|2|"
   , 17 => "Rubber Car Toy|11|"
   , 18 => "China Toy|15|"
)
;

// DOES IT LOOK RIGHT? YES
print_r($arr);

// DOUBLE STAR IS FIRST CATEGORY, SINGLE STAR IS SECOND CATEGORY, NO STAR IS LIST ITEM
$out = array();
foreach ($arr as $str)
{
    if (substr($str,0,2) == '**')
    {
        $first = $str;
    }
    elseif (substr($str,0,1) == '*')
    {
        $second = $str;
    }
    else
    {
        $out[]
        = str_replace('*', NULL, $first)
        . '|'
        . str_replace('*', NULL, $second)
        . '|'
        . $str;
    }
}
// DOES IT LOOK RIGHT? YES.
print_r($out);


// REVERSE THE ARRAY AND WORK UP FROM THE BOTTOM
$arr = array_reverse($arr);

// COLLECT THE SUB-ARRAYS HERE
$sub = array();
$end = array();

$out = array();
foreach ($arr as $str)
{
    if (substr($str,0,2) == '**')
    {
        $cat = str_replace('*', NULL, $str);
        $out[$cat] = array_reverse($sub);
        $sub = array();
    }
    elseif (substr($str,0,1) == '*')
    {
        $key = str_replace('*', NULL, $str);
        $sub[$key] = array_reverse($end);
        $end = array();
    }
    else
    {
        $end[] = $str;
    }
}

// REVERSE THE ARRAY TO ORIGINAL ORDER
$out = array_reverse($out);

// DOES IT LOOK RIGHT? YES.
print_r($out);

Open in new window

0
 
LVL 109

Accepted Solution

by:
Ray Paseur earned 450 total points
ID: 39656309
Here is a third example, starting at line 95.  It teaches how to make an array of objects.  With data-only structures like this, the array of objects has the advantage of simpler syntax and punctuation.  When you add class methods, the objects can take on a life of their own with all kinds of built-in functionality (think rows in a data base table, automatic tax calculations, etc).  This is not something that is available from arrays alone.  If you get very far in your programming studies, you will find the array of objects to be one of the most useful data constructs!

<?php // RAY_temp_tobece.php
error_reporting(E_ALL);
echo '<pre>';

// STARTING TEST DATA SET
$arr = Array
(
      0 => "**MAIN ITEM**"
   ,  1 => "*Self Defense*"
   ,  2 => "Pepper Spray|50|"
   ,  3 => "Stun Gun|75|"
   ,  4 => "A Hammer|20|"
   ,  5 => "*Sports*"
   ,  6 => "Baseball Cap|22|"
   ,  7 => "DuoGolf Stick|175|"
   ,  8 => "Portable Pool|1165|"
   ,  9 => "**ADDITIONAL ITEM**"
   , 10 => "*Food & Drinks*"
   , 11 => "Sprite|11|"
   , 12 => "7 Up|10|"
   , 13 => "Coca Cola|9|"
   , 14 => "**MISC ITEM**"
   , 15 => "*Kids*"
   , 16 => "Pair of Baloons|2|"
   , 17 => "Rubber Car Toy|11|"
   , 18 => "China Toy|15|"
)
;

// DOES IT LOOK RIGHT? YES
print_r($arr);

// DOUBLE STAR IS FIRST CATEGORY, SINGLE STAR IS SECOND CATEGORY, NO STAR IS LIST ITEM
$new = array();
foreach ($arr as $str)
{
    if (substr($str,0,2) == '**')
    {
        $first = $str;
    }
    elseif (substr($str,0,1) == '*')
    {
        $second = $str;
    }
    else
    {
        $new[]
        = str_replace('*', NULL, $first)
        . '|'
        . str_replace('*', NULL, $second)
        . '|'
        . $str;
    }
}
// DOES IT LOOK RIGHT? YES.
print_r($new);


// REVERSE THE ARRAY AND WORK UP FROM THE BOTTOM
$arr = array_reverse($arr);

// COLLECT THE SUB-ARRAYS HERE
$sub = array();
$end = array();

$out = array();
foreach ($arr as $str)
{
    if (substr($str,0,2) == '**')
    {
        $cat = str_replace('*', NULL, $str);
        $out[$cat] = array_reverse($sub);
        $sub = array();
    }
    elseif (substr($str,0,1) == '*')
    {
        $key = str_replace('*', NULL, $str);
        $sub[$key] = array_reverse($end);
        $end = array();
    }
    else
    {
        $end[] = $str;
    }
}

// REVERSE THE ARRAY TO ORIGINAL ORDER
$out = array_reverse($out);

// DOES IT LOOK RIGHT? YES.
print_r($out);


// SHOW HOW TO MAKE AN ARRAY OF OBJECTS
Class Item
{
    public function __construct($item, $dlm = '|')
    {
        $item = explode($dlm, $item);
        $this->main   = $item[0];
        $this->subcat = $item[1];
        $this->name   = $item[2];
        $this->price  = $item[3];
    }
}

// USE THE FIRST ARRAY WE CONSTRUCTED
foreach ($new as $str)
{
    $objs[] = new Item($str);
}
print_r($objs);

// SHOW HOW TO FIND THE "Sports" ITEMS
foreach ($objs as $obj)
{
    if ($obj->subcat == 'Sports')
    {
        echo PHP_EOL . "$obj->name PRICED AT $obj->price";
    }
}

Open in new window

HTH, ~Ray
0
 

Author Comment

by:tobece
ID: 39656359
Really thanks a lot Ray... I really really have to learn a lot from you for cleaner & shorter codes.
And also, the last solution is very nice which turns its output like pulling datas from MySQL :)

At first I was thinking of a solution like @duncanb7 until it get so complex and I cant handle it :(

Thanks all ...
0
 

Author Closing Comment

by:tobece
ID: 39656362
Really perfect results I received here ... :)
0
 
LVL 13

Expert Comment

by:duncanb7
ID: 39656380
Thanks your pt, I thought no pt since Ray_Paseur posted out with
his perfect code

it is good at least encourge people post out actively if they understand
the question & know the solution completely

have a nice day

Duncan
0
 
LVL 109

Expert Comment

by:Ray Paseur
ID: 39656407
Thanks for the points.  With MySQLi (and maybe PDO, not sure) you car retrieve rows of data from a data base query in the form of an object.  
http://php.net/manual/en/mysqli-result.fetch-object.php

The column names are the names of the properties in the object.  And you can create an object instance of any class you want from the results set.  This implies the ability to have object methods that use the results set automatically.  One example might be a data base that contained locations provided by a personnel sensor.  Upon querying the data base, the retrieved rows could automatically inject themselves into a master object to calculate directions and distances traveled by the sensor.  In a population of many sensors, this could enable you to detect when a person had left the group, etc.
0

Featured Post

3 Use Cases for Connected Systems

Our Dev teams are like yours. They’re continually cranking out code for new features/bugs fixes, testing, deploying, testing some more, responding to production monitoring events and more. It’s complex. So, we thought you’d like to see what’s working for us.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

This article is meant to give a basic understanding of how to use R Sweave as a way to merge LaTeX and R code seamlessly into one presentable document.
This article discusses four methods for overlaying images in a container on a web page
Learn the basics of lists in Python. Lists, as their name suggests, are a means for ordering and storing values. : Lists are declared using brackets; for example: t = [1, 2, 3]: Lists may contain a mix of data types; for example: t = ['string', 1, T…
Video by: Mark
This lesson goes over how to construct ordered and unordered lists and how to create hyperlinks.

831 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question