4
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

配列の値が数値だったら文字列にする(多次元配列対応)

Posted at

サーバからレスポンスを返す際に、数値と文字列が混在しているとフロント側でちょっと面倒と言われたので作りました。
多次元配列でもいけますが再帰処理を使っているので、あまりに階層が深い配列だとmemory_limitのエラーが出ちゃうかと思います。

public static function int2stringByArray( array $array ) {
		
		$responseArray = array();
		foreach ( $array as $key => $value ) {
			
			// 値が配列の場合
			if ( is_array( $value ) === TRUE ) {
				$responseArray[$key] = self::int2stringByArray( $value );
			// 値がintの場合
			} else if ( is_int( $value ) === TRUE ) {
				$responseArray[$key] = (string)$value;
			} else {
				$responseArray[$key] = $value;
			}
			
		}
		
		return $responseArray;
		
	}
4
4
6

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?