Home > Article > Backend Development > How to get a single value from an array in php
How to extract a single value from an array in php. Below, I will share with you a method for extracting a single value from an array in php. It has a good reference value and I hope it can help you.
1. Array arr
var_dump(arr) has the following values:
array (size=3) 'delete' => array (size=3) 0 => string 'HBSFlyRecode20170222-101501.txt' (length=31) 1 => string 'HBSFlyRecode20170222-105502.txt' (length=31) 2 => string 'HBSFlyRecode20170222-108803.txt' (length=31) 'new' => array (size=3) 0 => string 'HBSFlyRecode20170223-101504.txt' (length=31) 1 => string 'HBSFlyRecode20170223-105505.txt' (length=31) 2 => string 'HBSFlyRecode20170223-108806.txt' (length=31) 'old' => array (size=3) 0 => string 'HBSFlyRecode20170221-101507.txt' (length=31) 1 => string 'HBSFlyRecode20170221-105508.txt' (length=31) 2 => string 'HBSFlyRecode20170221-108809.txt' (length=31)
echo $arr['old'][0]; 打印出: HBSFlyRecode20170221-101507.txt
But if arr is in object form, the print result is as follows:
var_dump(arr) object(stdClass)[1] public 'delete' => array (size=3) 0 => string 'HBSFlyRecode20170222-101501.txt' (length=31) 1 => string 'HBSFlyRecode20170222-105502.txt' (length=31) 2 => string 'HBSFlyRecode20170222-108803.txt' (length=31) public 'new' => array (size=3) 0 => string 'HBSFlyRecode20170223-101504.txt' (length=31) 1 => string 'HBSFlyRecode20170223-105505.txt' (length=31) 2 => string 'HBSFlyRecode20170223-108806.txt' (length=31) public 'old' => array (size=3) 0 => string 'HBSFlyRecode20170221-101507.txt' (length=31) 1 => string 'HBSFlyRecode20170221-105508.txt' (length=31) 2 => string 'HBSFlyRecode20170221-108809.txt' (length=31)
You cannot use $arr['old'][0] to get the value, you can use the arr object The value of the foreach method that is common to arrays:
function getValue($arr){ foreach($arr as $key => $value){ if(is_array($value)){ getValue($value); }else{ echo $value."<br>"; } } }
If arr is in object form, you can convert the object into array form. Here is an example A shortcut:
1. $object_json = json_encode($arr); what you get is the object
$json = json_encode($arr,true); what you get It is pure json
2. What json_decode($object_json) and json_decode($json) get is an array object
json_decode($object_json,true) and json_decode($json,true) It’s an array
To sum up, you can convert an array object into an array:
arr=jsondecode(jsonencode(arr=jsondecode(jsonencode(arr,true),true);
project I found this problem in . It is recommended that when converting json and array in php, you should add true to the second parameter of json_encode() and json_decode(), that is:
##
json_encode(arr,true);jsondecode(arr,true);jsondecode(json,true);
The above is the detailed content of How to get a single value from an array in php. For more information, please follow other related articles on the PHP Chinese website!