将名称 - 值对检索到PHP数组中

时间:2012-06-04 05:32:02

标签: php multidimensional-array

我需要一些帮助。我有一个包含这个字符串的变量;

[{"id":"17","value":"123456789"},{"id":"18","value":"2012-06-13"},{"id":"19","value":"Kampala"},{"id":"20","value":"1"},{"id":"21","value":"500g"},{"id":"22","value":"Emirrets"},{"id":"23","value":"q"},{"id":"24","value":"q"},{"id":"25","value":"q"},{"id":"26","value":"q"},{"id":"27","value":"q"},{"id":"28","value":"q"},{"id":"29","value":"2"},{"id":"30","value":"987654321"},{"id":"45","value":"1"},{"id":"46","value":"1"}]

我需要检索每对的id和值,并在PHP中创建任何数组。

2 个答案:

答案 0 :(得分:1)

您可以使用json_decode并将第二个参数传递为true,以便它返回一个这样的数组

$json = '[{"id":"17","value":"123456789"},{"id":"18","value":"2012-06-13"},{"id":"19","value":"Kampala"},{"id":"20","value":"1"},{"id":"21","value":"500g"},{"id":"22","value":"Emirrets"},{"id":"23","value":"q"},{"id":"24","value":"q"},{"id":"25","value":"q"},{"id":"26","value":"q"},{"id":"27","value":"q"},{"id":"28","value":"q"},{"id":"29","value":"2"},{"id":"30","value":"987654321"},{"id":"45","value":"1"},{"id":"46","value":"1"}]';

$decoded = json_decode($json,true);


print_r($decoded);

Working Example

输出

Array
(
    [0] => Array
        (
            [id] => 17
            [value] => 123456789
        )

    [1] => Array
        (
            [id] => 18
            [value] => 2012-06-13
        )

    [2] => Array
        (
            [id] => 19
            [value] => Kampala
        )

    [3] => Array
        (
            [id] => 20
            [value] => 1
        )



    .......

)

您可以使用foreach来循环使用。

foreach($decoded as $de){
   // access id with $de['id']
   // access value with $de['value']

}

答案 1 :(得分:0)

你有一个json字符串。您可以使用函数json_decode将其转换为数组 检查此代码。

$str = '[{"id":"17","value":"123456789"},{"id":"18","value":"2012-06-13"}, {"id":"19","value":"Kampala"},{"id":"20","value":"1"},{"id":"21","value":"500g"},{"id":"22","value":"Emirrets"},{"id":"23","value":"q"},{"id":"24","value":"q"},{"id":"25","value":"q"},{"id":"26","value":"q"},{"id":"27","value":"q"},{"id":"28","value":"q"},{"id":"29","value":"2"},{"id":"30","value":"987654321"},{"id":"45","value":"1"},{"id":"46","value":"1"}]';
$array = json_decode($str);
foreach($array as $temp){
   echo "ID : ".$temp->id."\t Value: ".$temp->value;
   echo "<br />";
}