• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 353
  • Last Modified:

HELP re-arrange an array into 2 kinds of array

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
tobece
Asked:
tobece
  • 5
  • 2
  • 2
2 Solutions
 
Ray PaseurCommented:
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
 
Ray PaseurCommented:
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
 
duncanb7Commented:
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
Concerto Cloud for Software Providers & ISVs

Can Concerto Cloud Services help you focus on evolving your application offerings, while delivering the best cloud experience to your customers? From DevOps to revenue models and customer support, the answer is yes!

Learn how Concerto can help you.

 
Ray PaseurCommented:
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
 
Ray PaseurCommented:
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
 
tobeceAuthor Commented:
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
 
tobeceAuthor Commented:
Really perfect results I received here ... :)
0
 
duncanb7Commented:
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
 
Ray PaseurCommented:
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

Vote for the Most Valuable Expert

It’s time to recognize experts that go above and beyond with helpful solutions and engagement on site. Choose from the top experts in the Hall of Fame or on the right rail of your favorite topic page. Look for the blue “Nominate” button on their profile to vote.

  • 5
  • 2
  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now