多次元配列のforeach

<?php

$array = array(
		"code" => '1723',
		"name" => '日本電技',
		"market" => 'JQ',
		"price" => '3030',
		"PER" => '12.0',
		"PBR" => '1.37'
);

foreach($array as $key => $value){
	echo $key. "の値は" .$value. "です。<br>\n";
}
?>

codeの値は1723です。
nameの値は日本電技です。
marketの値はJQです。
priceの値は3030です。
PERの値は12.0です。
PBRの値は1.37です。

では、多次元配列でみてみましょう。

<?php

$stock = array();
$stock&#91;0&#93;&#91;'code'&#93; = '1968';
$stock&#91;0&#93;&#91;'name'&#93; = '太平電';
$stock&#91;0&#93;&#91;'price'&#93; = '2932';
$stock&#91;0&#93;&#91;'ratio'&#93; = '1.52%';
$stock&#91;1&#93;&#91;'code'&#93; = '1981';
$stock&#91;1&#93;&#91;'name'&#93; = '協和日成';
$stock&#91;1&#93;&#91;'price'&#93; = '851';
$stock&#91;1&#93;&#91;'ratio'&#93; = '-1.05%';
$stock&#91;2&#93;&#91;'code'&#93; = '2268';
$stock&#91;2&#93;&#91;'name'&#93; = 'サーティワン';
$stock&#91;2&#93;&#91;'price'&#93; = '4060';
$stock&#91;2&#93;&#91;'ratio'&#93; = '+0.12%';


foreach($stock as $id){
	foreach($id as $key => $value){
		echo "{$key} : {$value}<br>\n";
	}
	echo "<hr/>\n";
}
?>

var_dump(array_column($stock, ‘name’, ‘code’)); とすると、連想配列を作れる。

<?php

$stock = array();
$stock&#91;0&#93;&#91;'code'&#93; = '1968';
$stock&#91;0&#93;&#91;'name'&#93; = '太平電';
$stock&#91;0&#93;&#91;'price'&#93; = '2932';
$stock&#91;0&#93;&#91;'ratio'&#93; = '1.52%';
$stock&#91;1&#93;&#91;'code'&#93; = '1981';
$stock&#91;1&#93;&#91;'name'&#93; = '協和日成';
$stock&#91;1&#93;&#91;'price'&#93; = '851';
$stock&#91;1&#93;&#91;'ratio'&#93; = '-1.05%';
$stock&#91;2&#93;&#91;'code'&#93; = '2268';
$stock&#91;2&#93;&#91;'name'&#93; = 'サーティワン';
$stock&#91;2&#93;&#91;'price'&#93; = '4060';
$stock&#91;2&#93;&#91;'ratio'&#93; = '+0.12%';


var_dump(array_column($stock, 'name', 'code'));
?>

array(3) { [1968]=> string(9) “太平電” [1981]=> string(12) “協和日成” [2268]=> string(18) “サーティワン” }

Analytics API sample 3

<?php

	require_once 'vendor/autoload.php';

	$client_id = '';

	$view_id = '';

	$private_key = @file_get_contents('');

	$from = date('Y-m-d', strtotime('-1 month'));
	$to = date('Y-m-d');

	$dimensions = 'ga:date';
	$metrics = 'ga:visits';

	$option = array(
		'dimensions' => $dimensions,
		'max-results' => 10,
		'sort' => '-ga:visits',
		'start-index' => 11,
	);

	if(isset($_SESSION['service_token']))
	{
		$client->setAccessToken($_SESSION['service_token']);
	}

	$scopes = array('https://www.googleapis.com/auth/analytics.readonly');

	$credentials = new Google_Auth_AssertionCredentials($client_id, $scopes, $private_key);

	$client = new Google_Client();
	$client->setAssertionCredentials($credentials);

	if($client->getAuth()->isAccessTokenExpired())
	{
		$client->getAuth()->refreshTokenWithAssertion($credentials);
	}

	$_SESSION['service_token'] = $client->getAccessToken();

	$analytics = new Google_Service_Analytics($client);

	$data = $analytics->data_ga->get('ga:'. $view_id, $from, $to, $metrics, $option);



	$list = array();
	foreach($data['rows'] as $row => $value){
		$result = array();
		foreach($data['columnHeaders'] as $key => $header){
			$result[$header['name']] = $value[$key];
		}
		$list[] = $result;
	}
?>

<table>
		<thead>
				<tr>
						<th>pagepath</th>
						<th>visits</th>
				</tr>
		</thead>
		<tbody>
		<?php
				foreach($list as $val){
					echo "<tr>";
					foreach ($val as $data){
						echo "<td>$data</td>";
					}
					echo "</tr>";
				}
		?>
</tbody>
</table>

asort()・arsort()・ksort()・krsort()

キー・値の昇順・降順

<?php

$gainers = array('4664:RSC'=>'PER:-','4598:メドレックス'=>'PER:-','3791:IGポート'=>'PER:45.1','2385:総医研HD'=>'PER:63.7','4335:IPS'=>'PER:19.3','9385:ショーエイ'=>'PER:21.2','4976:東洋ドライ'=>'PER:17.8','7446:東北化学'=>'PER:13.2','3842:ネクスジェン'=>'PER:30.3','8705:岡藤HD'=>'PER:-');

asort($gainers);
print_r($gainers);
echo "<br><br>";
arsort($gainers);
print_r($gainers);
echo "<br><br>";
ksort($gainers);
print_r($gainers);
echo "<br><br>";
krsort($gainers);
print_r($gainers);
?>

Array ( [4664:RSC] => PER:- [8705:岡藤HD] => PER:- [4598:メドレックス] => PER:- [7446:東北化学] => PER:13.2 [4976:東洋ドライ] => PER:17.8 [4335:IPS] => PER:19.3 [9385:ショーエイ] => PER:21.2 [3842:ネクスジェン] => PER:30.3 [3791:IGポート] => PER:45.1 [2385:総医研HD] => PER:63.7 )

Array ( [2385:総医研HD] => PER:63.7 [3791:IGポート] => PER:45.1 [3842:ネクスジェン] => PER:30.3 [9385:ショーエイ] => PER:21.2 [4335:IPS] => PER:19.3 [4976:東洋ドライ] => PER:17.8 [7446:東北化学] => PER:13.2 [8705:岡藤HD] => PER:- [4598:メドレックス] => PER:- [4664:RSC] => PER:- )

Array ( [2385:総医研HD] => PER:63.7 [3791:IGポート] => PER:45.1 [3842:ネクスジェン] => PER:30.3 [4335:IPS] => PER:19.3 [4598:メドレックス] => PER:- [4664:RSC] => PER:- [4976:東洋ドライ] => PER:17.8 [7446:東北化学] => PER:13.2 [8705:岡藤HD] => PER:- [9385:ショーエイ] => PER:21.2 )

Array ( [9385:ショーエイ] => PER:21.2 [8705:岡藤HD] => PER:- [7446:東北化学] => PER:13.2 [4976:東洋ドライ] => PER:17.8 [4664:RSC] => PER:- [4598:メドレックス] => PER:- [4335:IPS] => PER:19.3 [3842:ネクスジェン] => PER:30.3 [3791:IGポート] => PER:45.1 [2385:総医研HD] => PER:63.7 )

sort関数

配列をソートする関数は多数ある。sort関数はアルファベット順。以下サンプルです。

<?php

$dealing = array('任天堂','ソニー','三菱UFJフィナンシャルグループ','三井住友フィナンシャルグループ');

sort($dealing);
print_r($dealing);		

?>

Array ( [0] => ソニー [1] => 三井住友フィナンシャルグループ [2] => 三菱UFJフィナンシャルグループ [3] => 任天堂 )

<?php

$dealing = array('7974:任天堂','6758:ソニー','8306:三菱UFJフィナンシャルグループ','8316:三井住友フィナンシャルグループ');

sort($dealing);
print_r($dealing);		

?>

Array ( [0] => 6758:ソニー [1] => 7974:任天堂 [2] => 8306:三菱UFJフィナンシャルグループ [3] => 8316:三井住友フィナンシャルグループ )

rsort()だと、昇順(逆)になります。
Array ( [0] => 8316:三井住友フィナンシャルグループ [1] => 8306:三菱UFJフィナンシャルグループ [2] => 7974:任天堂 [3] => 6758:ソニー )

shuffle()はランダム。
Array ( [0] => 8316:三井住友フィナンシャルグループ [1] => 7974:任天堂 [2] => 6758:ソニー [3] => 8306:三菱UFJフィナンシャルグループ )

natsort、natcasesortなどもあります。

bf・cc・zaif・btcのビットコイン価格をjsonで取得する(php)

各社が公開しているAPIから、ビットコイン価格をjsonで取得する。凄い時代になったもんだ。

<?php

	$array = array(
	'bf'=>array('name'=>'bitflyer','url'=>'https://api.bitflyer.jp/v1/getticker','ask'=>'best_ask',bid=>'best_bid'),
	'cc'=>array('name'=>'Coin Check','url'=>'https://coincheck.com/api/ticker','ask'=>'ask',bid=>'bid'),
	'zaif'=>array('name'=>'Zaif','url'=>'https://api.zaif.jp/api/1/ticker/btc_jpy','ask'=>'ask',bid=>'bid'),
	'btc'=>array('name'=>'BTCBOX','url'=>'https://www.btcbox.co.jp/api/v1/ticker/','ask'=>'sell',bid=>'buy'),

	);
		
		echo "<table>";
		foreach($array as $exchange){
			$json = file_get_contents($exchange[url]);
			$json = mb_convert_encoding($json, 'UTF8', 'ASCII,JIS,UTF-8,EUC-JP,SJIS-WIN');
			$arr = json_decode($json,true);
			echo "<tr><td><strong>".$exchange[name]."</strong></td><td>売り:".number_format($arr[($exchange[ask])]). "円</td><td>買い:".number_format($arr[($exchange[bid])]). "円</td></tr>";
		}
		echo "</table>";
		

?>

json_decode()

連想配列にします。

<?php

$url = "http://weather.livedoor.com/forecast/webservice/json/v1?city=130010";
$json = file_get_contents($url);
$json = mb_convert_encoding($json, 'UTF8', 'ASCII,JIS,UTF-8,EUC-JP,SJIS-WIN');
$arr = json_decode($json,true);

echo('<pre>');
print_r($arr);
echo('</pre>');
?>

では、東京の今日の天気を表示させてみましょう。

<?php

$url = "http://weather.livedoor.com/forecast/webservice/json/v1?city=130010";
$json = file_get_contents($url);
$json = mb_convert_encoding($json, 'UTF8', 'ASCII,JIS,UTF-8,EUC-JP,SJIS-WIN');
$arr = json_decode($json,true);

$time = strtotime($arr&#91;description&#93;&#91;publicTime&#93;);

echo "<b>東京:今日の天気</b><br>";
echo $arr[forecasts][0][telop]."<br>";
echo $arr[description]."<br>";
echo date("Y/m/d H:i:s", $time)."<br>";

?>

json_encode

値をJSON形式にて返します。

<?php

$arr = array('BTC'=> 893850, "ETH"=>93612, "XRP"=>89.00, "LTC"=> 13129.58, "DASH"=>58753.52);

echo json_encode($arr);

?>

output
{“BTC”:893850,”ETH”:93612,”XRP”:89,”LTC”:13129.58,”DASH”:58753.52}

では、連想配列でみてみましょう。

<?php

$arr = array(
	"code"=> "2317",
	"name"=> "システナ",
	"price"=>"4570",
	"volume"=>"492500",
	"index"=>array(
		"PER" => "37.0",
		"PBR" => "6.92",
		"rate" => "1.01"
		),
	"url" => "https://www.systena.co.jp/"
);

echo json_encode($arr, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE);

?>

{ “code”: “2317”, “name”: “システナ”, “price”: “4570”, “volume”: “492500”, “index”: { “PER”: “37.0”, “PBR”: “6.92”, “rate”: “1.01” }, “url”: “https:\/\/www.systena.co.jp\/” }

number_format

小数点以下が四捨五入
小数点以下も含むには、第二引数に桁数を記入

<?php
echo number_format(123.45, 1)
?>

面白くないので、連想配列で見てみましょう。

<?php

$array = &#91;
	&#91;"1月30日", 3210,3205&#93;,
	&#91;"1月29日", 3280,3290&#93;,
	&#91;"1月28日", 3285,3310&#93;,
	&#91;"1月27日", 3395,3300&#93;
&#93;;

foreach($array as $trade){
	$dif = number_format(($trade&#91;2&#93; -$trade&#91;1&#93;) / $trade&#91;2&#93;, 4);
	echo $trade&#91;0&#93;. ":" .$dif. "(買値:" .$trade&#91;1&#93;. "、売値:" .$trade&#91;2&#93;.")<br>";
}

?>

Google Analytics Dimensions & Metrics Explorer

こちらにディメンション一覧が掲載されております。
https://developers.google.com/analytics/devguides/reporting/core/dimsmets

例:
ga:users : The total number of users for the requested time period.
ga:newUsers : The number of sessions marked as a user’s first sessions.
ga:1dayUsers : Total number of 1-day active users for each day in the requested time period. At least one of ga:nthDay, ga:date, or ga:day must be specified as a dimension to query this metric. For a given date, the returned value will be the total number of unique users for the 1-day period ending on the given date.

and so on.

使えそうなところとして
-ga:newUsers:The total number of users for the requested time period.
-ga:hits:Total number of hits for the view
-ga:referralPath:The path of the referring URL (e.g., document.referrer). If someone places on their webpage a link to the property, this is the path of the page containing the referring link.
-ga:pageTitle:The page’s title. Multiple pages might have the same page title.
-ga:pageviews:The total number of pageviews for the property.
-ga:avgTimeOnPage:
-ga:date:The date of the session formatted as YYYYMMDD.
-ga:deviceCategory:The type of device: desktop, tablet, or mobile.

ceil()

小数点以下を切り上げます。

<?php

print round(234.567,2)."<br>";
print floor(234.567)."<br>";
print ceil(234.567)."<br>";
?>

消費税計算をしてみます。

<?php

$market1 = 140000;
$market2 = 121824;
$market3 = 99799;

echo "A社のスマートフォン定価は、".$market1."円で、税込み価格は、<mark>端数切り捨て</mark>の".floor($market1*1.08)."円です。<br>";
echo "B社のスマートフォン定価は、".$market2."円で、税込み価格は、<mark>端数切り上げ</mark>の".ceil($market2*1.08)."円です。<br>";
echo "C社のスマートフォン定価は、".$market3."円で、税込み価格は、<mark>端数四捨五入</mark>の".round($market3*1.08, 1)."円です。<br>";
?>