배열에서 그룹별로 합계 구하기(group by)

배열에서 그룹별로 합계 구하기(group by)

// 배열중 같은 항목 그룹별로 합계 구하기(group by)

 

// mysql 의 group by 기능

 

$arr = array('돼지고기*400000', '돼지고기*400000', '쇠고기*250000', '쇠고기*400000', '양고기*250000');

foreach ($arr as $k => $v) {

$arr = explode('*', $v); 

$arrA[$arr[0]] += $arr[1];

}

print_r($arrA); // Array ( [돼지고기] => 800000 [쇠고기] => 650000 [양고기] => 250000 ) 

 

관련글  http://sir.co.kr/qa/?wr_id=40455 

[클래스] 여러 종류의 객체를 하나의 배열로 다루기

[클래스] 여러 종류의 객체를 하나의 배열로 다루기

class Buyer {             

var $money = 1000,

$cart = array(), // 구입한 제품을 저장하기 위한 배열 

$i = 0; // Product배열 cart에 사용될 index 

 

function buy(Product $p) { 

if ($p->price > $this->money) {

println('잔액이 부족하여 ' . $p . '를 살수 없습니댜.');

return;

}

$this->money -= $p->price;

$this->add($p);

/*

            가진 돈과 물건의 가격을 비교해서 가진 돈이 적으며 종료한다.

            가진 돈이 충분하면, 제품의 가격을 가진 돈에서 빼고

            장바구니에 구입한 물건을 담는다. (add메서드 호출)

*/

 

function add(Product $p) {

$this->cart[$this->i] = $p;

$this->i++;

/*

    물건을 장바구니(cart)에 저장한다. 그리고 i의 값을 1 증가시킨다.

*/

} // add(Product p)

 

function summary() {

$itemList = '';

$sum = 0;

for ($i=0; $i<count($this->cart); $i++) {

$this->itemList .= $this->cart[$i] . ',';

$this->sum += $this->cart[$i]->price;

}

 

println('구입한 물건 : ' . $this->itemList);

println('사용한 금액 : ' . $this->sum);

println('남은 금액 : ' . $this->money);

/*

장바구니에 담긴 물건들의 목록을 만들어 출력한다.

장바구니에 담긴 물건들의 가격을 모두 더해서 출력한다.

물건을 사고 남은 금액(money)를 출력한다.

*/

} // summary()

 

class Product {

var $price; // 제품의 가격

 

function __construct($price) {

$this->price = $price;

}

}

 

class Tv extends Product {

function __construct() { 

Parent::__construct(100); 

}

 

 public function __toString() {

        return 'Tv'; 

    }

}

 

class Computer extends Product {

function __construct() { 

Parent::__construct(200); 

}

 

public function __toString() {

return 'Computer';

}

}

 

class Audio extends Product {

function __construct() { 

Parent::__construct(50); }

 

public function __toString() {

return 'Audio'; 

}

}

 

$b = new Buyer();

$b->buy(new Tv());

$b->buy(new Computer());

$b->buy(new Tv());

$b->buy(new Audio());

$b->buy(new Computer());

$b->buy(new Computer());

$b->buy(new Computer());

 

$b->summary();

 

// 줄바꿈 출력

function println($arg) {

echo $arg.'<br />';

/* 출력

​ 잔액이 부족하여 Computer를 살수 없습니댜.

구입한 물건 : Tv,Computer,Tv,Audio,Computer,Computer,
사용한 금액 : 850

남은 금액 : 150 

*/

[클래스] abstract 추상클래스

[클래스] abstract 추상클래스

/*

추상클래스 자체로는 클래스로서의 역할을 다 못하지만,

새로운 클래스를 작성하는데 있어서 바탕이 되는 조상클래스로서 중요한 의미를 갖는다.

새로운 클래스를 작성할때 아무것도 없는 상태에서 시작하는 것보다는 완전하지는 못하더라도

어느정도 틀을 갖춘상태에서 시작하는 것이 나을것이다.

*/

 

abstract class Board {

    public function __construct(){

        echo('게시판입니다.<br>');

    }

    abstract function skin();

}

 

class Latest extends Board {

    public function skin(){

        echo('최신글스킨.<br>');

    }

}

 

class Basic extends Board {

    public function skin(){

        echo('일반형스킨.<br>');

    }

}

 

$latest = new Latest();

$latest->skin();

$basic = new Basic();

$basic->skin(); 

 

/* 출력 

게시판입니다.

최신글스킨.
게시판입니다.

일반형스킨. 

*/

개발하면서 도움이 많이 되는 array 함수 extract 소개합니다

개발하면서 도움이 많이 되는 array 함수 extract 소개합니다

$array = array('test' => 'ok');

extract($array);

echo $test;

이렇게 사용하면 됩니다.

array를 변수로 변환됩니다. 

[알고리즘] 배열 역순

[알고리즘] 배열 역순
// 배열 역순

function reverse(&$a) {
    $start = 0; // 배열시작 인덱스 
    $count = count($a);
$end = $count - 1; // 배열끝 인텍스,  0 부터 시작하니 배열갯수에서 1을 뺌

    while ($start < $count/2) {
        /* 요소 교체 */
        $temp = $a[$end];
        $a[$end--] = $a[$start];
        $a[$start++] = $temp;
    }
}
$a = array(1,2,3,4,5,6,7,8,9);

foreach ($a as $k => $v) echo($a[$k]);
echo '<br />';

reverse($a);

foreach ($a as $k => $v) echo($a[$k]);

 

/* output 

123456789

987654321

*/ 

[알고리즘] 배열로 구현하는 스택(stack)

[알고리즘] 배열로 구현하는 스택(stack)
// 배열로 구현하는 스택 

// 스택 최대크기 5

define('MAX', 5);
$top = 0;
$stack = array();
 
function init_stack() {
    Global $top;
    $top = -1;
}
 
function push($t) {
    Global $top, $stack;
 
    if ($top >= MAX - 1) {
        println('Stack overflow.');
return -1;    
}
    $stack[++$top] = $t;
}
 
function pop() {
    Global $top, $stack;
 
    if ($top < 0) {
        println('Stack underflow.');
return -1;
    } 
    return $stack[$top--];
}
 
function print_stack() {
    Global $top, $stack;
 
    println('Stack contents : Top ----> Bottom');
    for ($i = $top; $i >= 0; $i--) 
        println($stack[$i]);
}
 
init_stack();
 
println('Push 1, 2, 3');
push(1);
push(2);
push(3);
 
print_stack();
println();
 
$i = pop();
println("Pop ". $i);
print_stack();
println();
 
println('Push 4, 5, 6');
push(4);
push(5);
push(6);
 
print_stack();
println();
 
println('Now stack is full, push 7');
push(7);
print_stack();
println();
 
println('Initialize stack');
init_stack();
print_stack();
println();
 
println('Now stack is empty');
println('Pop');
pop();
 
 
println('Push 7, 8');
push(7);
push(8);
print_stack();
println();
 
function println($val='') {
echo $val.'<br />';

 

/* output

Push 1, 2, 3

Stack contents : Top ----> Bottom
3
2
1

Pop 3
Stack contents : Top ----> Bottom
2
1

Push 4, 5, 6
Stack contents : Top ----> Bottom
6
5
4
2
1

Now stack is full, push 7
Stack overflow.
Stack contents : Top ----> Bottom
6
5
4
2
1

Initialize stack
Stack contents : Top ----> Bottom

Now stack is empty
Pop
Stack underflow.
Push 7, 8
Stack contents : Top ----> Bottom
8
7

*/

[알고리즘] 단순 연결 리스트를 이용한 스택(stack)

[알고리즘] 단순 연결 리스트를 이용한 스택(stack)

/*

연결 리스트, 링크드 리스트(linked list)는 각 노드가 데이터와 포인터를 가지고 한 줄로 연결되어 있는 방식으로 

데이터를 저장하는 자료 구조이다. 

이름에서 말하듯이 데이터를 담고 있는 노드들이 연결되어 있는데, 

노드의 포인터가 다음이나 이전의 노드와의 연결을 담당하게 된다. 

연결 리스트의 종류로는 단순 연결 리스트, 이중 연결 리스트 등이 있다. 

*/

// 단순 연결 리스트를 이용한 스택의 구현

 

class Node {

    public $key;

    public $next = Node;

 

$head = new Node;

$tail = new Node;

 

function init_stack() {

    Global $head, $tail;

 

    $head->next = $tail;

    $tail->next = $tail;

}

 

function clear_stack() {

    Global $head, $tail;

    $t = Node;

    $s = Node;

 

    $t = $head->next;

    while ($t != $tail) {

        $s = $t;

        $t = $t->next;

        $s = null;

    }

    $head->next = $tail;

}

 

function push($k) {

    Global $head, $tail;

    $t = new Node;

   

    if ($t == NULL) {

        println("   Out of memory...");        

    }

  

    $t->key = $k;

    $t->next = $head->next;

    $head->next = $t;

}

 

function pop() {

    Global $head, $tail;

    $t = new Node;

 

    if ($head->next == $tail)  /* if empty */ {

        println("  Stack underflow.");

        return -1;

    }

    $t = $head->next;

    $i = $t->key;

    $head->next = $t->next;

    $t = null;

    

    return $i;

}

 

function print_stack() {

    Global $head, $tail;

    $t = new Node;

 

    $t = $head->next;

    println("  Stack contents : Top ----> Bottom");

    while ($t != $tail) {

        println($t->key);

        $t = $t->next;

    }

}

 

init_stack();

 

println('Push 1, 2, 3');

push(1);

push(2);

push(3);

print_stack();

 

$i = pop();

println('Pop '.$i);

print_stack();

 

println('Push 4, 5, 6');

push(4);

push(5);

push(6);

print_stack();

 

println('Initialize stack');

clear_stack();

print_stack();

 

println('Now stack is empty,');

println('Pop');

$i = pop();

print_stack();

 

function println($str=''){

    echo $str.'<br />';

 

/* output

Push 1, 2, 3

Stack contents : Top ----> Bottom
3
2
1
Pop 3
Stack contents : Top ----> Bottom
2
1
Push 4, 5, 6
Stack contents : Top ----> Bottom
6
5
4
2
1
Initialize stack
Stack contents : Top ----> Bottom
Now stack is empty,
Pop
Stack underflow.

Stack contents : Top ----> Bottom 

*/

[알고리즘] 이중연결리스트를 이용한 큐(queue)

[알고리즘] 이중연결리스트를 이용한 큐(queue)

<?

/* 

큐(queue)는 컴퓨터의 기본적인 자료 구조의 한가지로, 

먼저 집어 넣은 데이터가 먼저 나오는 FIFO (First In First Out)구조로 저장하는 형식을 말한다 

 

http://terms.naver.com/entry.nhn?docId=834442&cid=42344&categoryId=42344

http://ko.wikipedia.org/wiki/%ED%81%90_(%EC%9E%90%EB%A3%8C_%EA%B5%AC%EC%A1%B0)

*/

 

// 시작노드와 끝노드만 남기고 나머지 노드 삭제

function clear_queue() {

    global $head, $tail;

 

    $t = new dnode;

    $s = new dnode;

    $t = $head->next;

    while ($t != $tail) {

        $s = $t;

        $t = $t->next;

        $s = null;

    }

    $head->next = $tail;

    $tail->prev = $head;

}

 

// 마지막 노드 앞에 새 노드 삽입

function put($k) {

    global $head, $tail;

 

    $t = new dnode;

 

    $t->key = $k;

    $tail->prev->next = $t;

    $t->prev = $tail->prev;

    $tail->prev = $t;

    $t->next = $tail;

 

    return $k;

}

 

// 큐에 시작노드 다음 노드의 key 값 가져오기

function get() {

    global $head, $tail;

 

    $t = new dnode;

    $i = 0;

    $t = $head->next;

    if ($t == $tail) {

        printf('<br />    Queue underflow.');

        return -1;

    }

    $i = $t->key;

    $head->next = $t->next;

    $t->next->prev = $head;

    $t = null;

    return $i;

}

 

// 큐에 저장된 key 값 보여주기

function print_queue() {

    global $head, $tail;

 

    $t = $head->next;

    printf('<br />  Queue contents : Front ----> Rear<br />');

    while ($t != $tail) {

        printf('%2d', $t->key);

        $t = $t->next;

    }

}

 

// 노드정의

class dnode {

    public $key = 0, 

$prev = null, 

$next = null;

 

$head = new dnode; // 시작노드

$tail = new dnode; // 끝노드

 

$head->prev = $head;

$head->next = $tail;

$tail->prev = $head;

$tail->next = $tail;

 

printf('<br />Put 1, 2, 3, 4, 5, 6');

put(1);

put(2);

put(3);

put(4);

put(5);

put(6);

print_queue();

 

echo ('<br /><br />Get');

$i = get();

printf('<br />   getting value is %d', $i);

print_queue();

 

printf('<br /><br />Put 7, 8, 9, 1');

put(7);

put(8);

put(9);

put(1);

print_queue();

 

printf('<br /><br />Put 2');

put(2);

print_queue();

 

printf('<br /><br />Initialize queue');

clear_queue();

print_queue();

 

printf('<br /><br />Now queue is empty');

echo ('<br />Get');

$i = get();

printf('<br />   getting value is %d', $i);

print_queue();

?> 

범위사이에서 중복없이 랜덤(random)으로 뽑기

범위사이에서 중복없이 랜덤(random)으로 뽑기function random($min, $max, $num) {

$arr = array();
while ($num > count($arr)) {
$i = rand($min, $max);
$arr[$i] = $i; 
}
return $arr;
}

foreach (random(1,9, 5) as $v) echo $v;

 

/* output

1과 9사이에서 랜덤으로 중복없이 5개 뽑기

43186

*/

 

[알고리즘] 하노이의 탑

[알고리즘] 하노이의 탑

/*

하노이의 탑 

http://ko.wikipedia.org/wiki/%ED%95%98%EB%85%B8%EC%9D%B4%EC%9D%98_%ED%83%91 

 

1. 한번에 하나만 이동.(모든 원반을 마지막 기둥으로.)

2. 작은원반 위로 큰 원반을 이동할 수 없다.
3. 가장위의 원반만 이동가능.

알고리즘
1. 기둥 1에서 N-1개의 원반을 기둥 2로 옮긴다
2. 기둥 1에서 1개의 원반을 기둥 3으로 옮긴다.
3. 기둥 2에서 N-1개의 원반을 기둥 3으로 옮긴다.

from 기둥에서 to기둥으로 by기둥을 이용하여 옮기기
from : 이동할 기둥
to : 이동되어질 기둥

hanoi(원반수, 이동할 기둥, 나머지기둥, 이동되어질 기둥)
*/

 

function move($from, $to) {

    printf("<br />Move from %d to %d", $from, $to);

}

 

function hanoi($n, $from, $by, $to) {

    if ($n == 1)

        move($from, $to);

    else {

        hanoi($n-1, $from, $to, $by); // 1

        move($from, $to); // 2

        hanoi($n-1, $by, $from, $to); // 3

   }

}

 

$height = 3;

printf("Height of HANOI tower is %d <br />",$height);

hanoi($height, 1, 2, 3); 

 

/* output

Height of HANOI tower is 3 


Move from 1 to 3
Move from 1 to 2
Move from 3 to 2
Move from 1 to 3
Move from 2 to 1
Move from 2 to 3

Move from 1 to 3 

*/