[英]How to read json encoded value using php?
我在PHP中有一個名為$ partialSegments的變量。 我想遍歷它並在遇到operator
或rOperandValue
等時執行操作。我在函數調用中收到它,因此在進行
function named(say):
public function convertJsCode($partialSegments){
//logic
}
我在邏輯上掙扎
"segments":{"type":"custom","partialSegments":[{"type":"7","operator":11,"rOperandValue":["windows xp"],"prevLogicalOperator":null},{"type":"8","operator":11,"rOperandValue":["other"],"prevLogicalOperator":"AND"}]}}
<?php
$json = '{"segments":{"type":"custom","partialSegments":[{"type":"7","operator":11,"rOperandValue":["windows xp"],"prevLogicalOperator":null},{"type":"8","operator":11,"rOperandValue":["other"],"prevLogicalOperator":"AND"}]}}';
$parsed = json_decode($json, true);
foreach($parsed["segments"]["partialSegments"] as $val) {
$operator = $val["operator"]; // operator value
$rOperandValue = $val["rOperandValue"][0]; // rOperandValue value
}
?>
步驟1:使用json_decode();
將json編碼的數據轉換為php數組json_decode();
功能。 此函數接收兩個參數:第一個是:應該解碼的json_encoded數據,第二個是: boolean(TRUE or FALSE)
。 傳遞第二個參數為TRUE,將json編碼值轉換為php數組,如果傳遞false,它將返回php對象。
第2步:迭代php數組,並將邏輯設置為“魅力”。
<?php
$json = '{"segments":{"type":"custom","partialSegments":[{"type":"7","operator":11,"rOperandValue":["windows xp"],"prevLogicalOperator":null},{"type":"8","operator":11,"rOperandValue":["other"],"prevLogicalOperator":"AND"}]}}';
$parsed = json_decode($json, true);
foreach($parsed as $single){
$segments = $single['partialSegments'];
//print_r($single);
foreach($segments as $segment){
echo 'operator:'. $segment['operator'].'<br>';
print_r($segment['rOperandValue']);
// put your logic based on 'operator' or 'rOperandValue'
}
}
?>
建議:不要使用硬代碼索引來處理類似$segment['rOperandValue'][0]
的數組。 數組可以為空。 即:如果您想在$segment['rOperandValue'] use in_array()
找到一個值時執行任何操作,請$segment['rOperandValue'] use in_array()
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.