안녕하세요

프로그램 과정에서 막혔던 문제들에 대한 해결책 정리


페이지 목록

레이블이 PHP인 게시물을 표시합니다. 모든 게시물 표시
레이블이 PHP인 게시물을 표시합니다. 모든 게시물 표시

2018년 2월 21일 수요일

PHP mssql nText 사용방법

Text로 cast 해서 사용하면 된다.

이걸 몰라서 몇시간을 헤매었다...

  • SELECT CAST(field1 AS TEXT) AS field1 FROM table

2018년 2월 13일 화요일

PHP 우측 검색 (마지막으로 나오는 문자 검색)

strrchr

(PHP 4, PHP 5, PHP 7)
strrchr — Find the last occurrence of a character in a string

Description ¶

string strrchr ( string $haystack , mixed $needle )
This function returns the portion of haystack which starts at the last occurrence of needle and goes until the end of haystack.

출처: http://php.net/manual/en/function.strrchr.php

PHP to JSON(PHP class를 JSON으로 변경하는 방법)

PHP to JSON- How to serialize PHP class to JSON format?

If you are using PHP to implement REST API, you will come across this question. The answer to this, in general, is really simple.
PHP comes with two functions json_encode and json_decode, for encoding a PHP object into JSON and JSON string into PHP object respectively.
Check out the manual at Php.Net for the full details of this function.
The call is simple $j = json_encode($v);
$j contains the JSON for $v which can be an array, object or scalar variable.
However, here are a few limitations to json_encode.
  1. If you have strings stored in the object your encoding, they have to be UTF-8 strings or you need to convert them to UTF-8 using utf8_encode before calling json_encode
  2. If you have member variables that are marked as private, json_encode can’t see them.
  3. Associative arrays will be represented as objects. Sequential arrays will be represented as arrays in JSON. You can force them to be represented as objects by either casting the variable to object or pass in the option JSON_FORCEOBJECT
Being able to expose private and protected variables is very important. This can be done in various ways. You can use an Iterator like an ArrayIterator and call json_encode on that. The solution I am going to outline involves writing your own custom encode function that uses json_encode.
As an example you take the following classes in PHP. JsonTest contains JSon_Test1 which in turn contains JSonTest_2.
class Marshall
{
public function propvalues()
{
return get_object_vars($this);
}
}
class JSonTest_2 extends Marshall
{
public $arr2;
public function __construct()
{
$this->arr2 = array(1 => “stest”, 4 =>”stest2″, 3=>5.1);
}
}
class JSonTest_1 extends Marshall
{
public $arr1;
public $j2;
private $jp2;
public function __construct()
{
$this->arr1 = array(“test”, “test2”);
$this->j2 = new JSonTest_2();
$this->jp2 = “jp2”;
}
public function propvalues()
{
return array(“arr1” =>$this->arr1, “j2″=>$this->j2->propvalues(), “jp2″=>$this->jp2);
}
}
class JsonTest extends Marshall
{
private $arrActuary = array();
public $jt1;
private $jt11;
private $arrTestM = array();
public function __construct()
{
$this->jt1 = new JSonTest_1();
$this->jt11 = new JSonTest_1();
$this->arrTestM = array(1 =>”value”, “test” =>100.21);
}
public function propvalues()
{
return array(“jt1″=>$this->jt1->propvalues(), “jt11″=>$this->jt11->propvalues(), “arrTestM”=>$this->arrTestM);
}
}
class JSon
{
static public function encode($o)
{
if(is_a($o, “Marshall”))
return json_encode($o->propvalues());
return json_encode($o);
}
}
The following code will call normal json_encode passing in $j and then call the special encode on $j.
$j = new JsonTest();
echo “normal encode”;
echo json_encode($j);
echo “special encode”;
echo JSon::encode($j);
This will echo the following two lines: (You can pretty print these to make them more readable etc.)
normal encode
{“jt1”:{“arr1”:[“test”,”test2″],”j2″:{“arr2”:{“1″:”stest”,”4″:”stest2″,”3″:5.1}}}}
special encode
{“jt1”:{“arr1”:[“test”,”test2″],”j2″:{“arr2”:{“1″:”stest”,”4″:”stest2″,”3″:5.1}},”jp2″:”jp2″},”jt11″:{“arr1”:[“test”,”test2″],”j2″:{“arr2”:{“1″:”stest”,”4″:”stest2″,”3″:5.1}},”jp2″:”jp2″},”arrTestM”:{“1″:”value”,”test”:100.21}}
I define a class called Marshall which when inherited automatically exposes all the public variables as an array. If you override the function propvalues in the inherited class as is done in the class JSonTest_1, you will be able to iterate over the private and protected variables too.
I also defined a helper class JSon with static function encode which calls json_encode on the object if it does not inherit from Marshall otherwise it will call propvalues function and json_encode the return value.
Here we make use of two properties of json_encode to achieve this. First one is the fact that json_encode recursively encodes the objects. Second one is that associative arrays are encoded as objects. The second property is the one that’s used in propvalues where we are constructing the associative array with the private, protected and public variables.
Note that propvalues itself can check if the contained class in this case JSonTest_2 is a Marshall class and call propvalues on it.
The code above has an advantage over normal json_encode function in that you can transform the class to be different from what it is in PHP when you serialize in JSON.. can be selective about which member variables in the class you want to add to JSON. You can also decide what to name them.
(Note – json_encode is available in 5.2 version or later and get_object_vars in PHP version 4.0 or later)

출처: https://mofintodev.wordpress.com/2013/07/09/php-to-json-how-to-serialize-php-class-to-json-format/

2018년 2월 12일 월요일

[PHP] Debug 방법

error_reporting(E_ALL); ini_set("display_errors", 1);
를 맨위에 붙이면 왜 에러가 났는지 Warning이 떴는지 출력이 된다.

PHP Debug에 꼭 필요하다.

2018년 1월 30일 화요일

PHP Left, Right

< 방법1 >

substr('123456', 0, 2) = 12 : asp 의 left 와 같은 효과
substr('123456', 2) = 3456 : asp 엔 없지만 파라미터 2 만큼 왼쪽에서 제외하고 나머지 부분들을 다 긁어옴
substr('123456', -2) = 56 : asp 의 right 와 같은 효과
substr('123456', 2, 5)3456 : asp 의 mid 와 같은 효과

주의 할점은 left 와 mid 함수와 substr 의 차이는 스트링의 첫 주소값을 asp 는 1로 php는 0 으로 한다는 점이다



< 방법2 >

ASP의 내장함수인  left() ,  right() 와 유사한 기능을 하기 위해 만들어진 PHP용 Function
용도 : 글자수 자르기

<?php
function right($value, $count){
  $value = substr($value, (strlen($value) - $count), strlen($value));
  return $value;
}

function left($string, $count){
  return substr($string, 0, $count);
}

$str ="오늘은 기분좋은하루입니다";
$str2 = left($str, 3);
echo $str2;
?>

- 출력결과
오




참고자료
http://www.dreamincode.net/forums/showtopic59918.htm 
http://gooranet.tistory.com/20 

2018년 1월 18일 목요일

PHP Array Count

배열 크기 즉, "배열의 각 구성 요소(Element)의 개수"를 구하려면 count() 함수 속에 배열명을 넣어주면 됩니다.

그런데 count() 함수는, "요소 개수가 0인 배열"과 "존재하지 않는 배열" 모두 0을 반환하기에 혼란스러운 점이 있습니다. 이때는 isset() 함수를 사용하여 그 배열이 실재하는지 우선 체크하는 것이 좋습니다.

아래 예제의 safeCount() 라는 함수를 사용하면, 배열이 존재하지 않을 때에는 -1을 반환하게 할 수 있습니다.

배열 사이즈 / 요소 갯수 얻기 예제


파일명: example.php
<html>
<head>
<title>PHP Example</title>
</head>

<body>

<?php

  $a = array(1, 2, "AAA", "BBB");
  echo count($a) . "<br />\n";
  // 출력 결과: 4

  $b = array("자장면", "짬뽕", "탕수육");
  echo count($b) . "<br />\n";
  // 출력 결과: 3


  // 요소가 하나도 없으면 당연히 0
  $b = array();
  echo count($b) . "<br />\n";
  // 출력 결과: 0




  /////////////////////////////////////////////
  // 존재하지 않는 배열도 0으로 나오므로 주의
  echo count($tt) . "<br />\n";
  // 출력 결과: 0


  // 존재하지 않는 배열은 -1을 반환하기
  echo safeCount($tt) . "<br />\n";
  // 출력 결과: -1

  // 존재하는 배열만 요소 개수 출력하기
  echo safeCount($a) . "<br />\n";
  // 출력 결과: 4



function safeCount($array) {
  if (isset($array)) return count($array);
  return -1;
}

?>

</body>
</html>

2016년 12월 27일 화요일

[php] GetTime

<?php
$t=time();
echo($t . "<br>");
echo(date("Y-m-d",$t));
?>

출처: http://www.w3schools.com/php/func_date_time.asp