我有以下数组,我想在其中获得type
and(如果设置了任何amount
值)值(默认值应为1)。我该怎么做?
array(10) {
[0]=> array(1) { ["type"]=> string(3) "EMPTY" }
[1]=> array(1) { ["type"]=> string(7) "BEER" }
[2]=> array(2) { ["type"]=> string(8) "BEEF" ["amount"]=> int(3) }
[3]=> array(1) { ["type"]=> string(3) "WOOD" }
[4]=> array(1) { ["type"]=> string(3) "CHEESE" }
[5]=> array(1) { ["type"]=> string(3) "EMPTY" }
[6]=> array(1) { ["type"]=> string(3) "EMPTY" }
[7]=> array(1) { ["type"]=> string(3) "EMPTY" }
[8]=> array(1) { ["type"]=> string(3) "EMPTY" }
[9]=> array(1) { ["type"]=> string(3) "EMPTY" }
}
编辑:嗯,像以前一样,我已经使用了foreach进行了尝试。但是由于这已经不是JSON了,我死了
foreach($json as $key => $moreJson)
{
$json[$key] = json_decode($moreJson);
}
echo '<p> User data for Player is 1 ', $json['type'][3];
但这给了我:
Warning: json_decode() expects parameter 1 to be string, array given in XX on line 19
你可以这样做
$new_array = array();
foreach($array as $item){
if( !array_key_exists('amount',$item) ){
$item['amount'] = 1;
}
$new_array[] = $item;
}
甚至没有花括号就更好了,因为我们只在if语句中执行一行代码。
$new_array = array();
foreach($array as $item){
if( !array_key_exists('amount',$item) )
$item['amount'] = 1;
$new_array[] = $item;
}
甚至没有$ new_array和花括号也更好。您可以使用&通过引用分配该数组值。
foreach($array as &$item)
if( !array_key_exists('amount',$item) )
$item['amount'] = 1;
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句