Solved

HELP re-arrange an array into 2 kinds of array

Posted on 2013-11-18
9
333 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 108

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 108

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
 
LVL 108

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
Top 6 Sources for Identifying Threat Actor TTPs

Understanding your enemy is essential. These six sources will help you identify the most popular threat actor tactics, techniques, and procedures (TTPs).

 
LVL 108

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 108

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

What Security Threats Are You Missing?

Enhance your security with threat intelligence from the web. Get trending threat insights on hackers, exploits, and suspicious IP addresses delivered to your inbox with our free Cyber Daily.

Join & Write a Comment

Active Directory replication delay is the cause to many problems.  Here is a super easy script to force Active Directory replication to all sites with by using an elevated PowerShell command prompt, and a tool to verify your changes.
Since pre-biblical times, humans have sought ways to keep secrets, and share the secrets selectively.  This article explores the ways PHP can be used to hide and encrypt information.
Learn the basics of if, else, and elif statements in Python 2.7. Use "if" statements to test a specified condition.: The structure of an if statement is as follows: (CODE) Use "else" statements to allow the execution of an alternative, if the …
The viewer will learn how to create and use a small PHP class to apply a watermark to an image. This video shows the viewer the setup for the PHP watermark as well as important coding language. Continue to Part 2 to learn the core code used in creat…

758 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

Need Help in Real-Time?

Connect with top rated Experts

22 Experts available now in Live!

Get 1:1 Help Now