简体   繁体   中英

How i can access this php array string value

 array(3) { [20]=> string(43) "{"shortname":"testvqweq","fullname":"test"}" [21]=> string(51) "{"shortname":"bwqbdwqbwqeb","fullname":"qwbdwqbwq"}" [22]=> string(48) "{"shortname":"wqdwqdwqdw","fullname":"dwqwqdwq"}" }

I want to access shortname, fullname from array like: Testvqweqe test

Here is an example that will clear things up for you I hope:

<?php

$array = [
    "20" => '{"shortname":"testvqweq","fullname":"test"}',
    "21" => '{"shortname":"bwqbdwqbwqeb","fullname":"qwbdwqbwq"}',
    "22" => '{"shortname":"wqdwqdwqdw","fullname":"dwqwqdwq"}',
];

echo '<pre>';
print_r($array);

foreach($array as $json){
    echo '<pre>';
    $j2a = json_decode($json,true);
    print_r($j2a['shortname']);
}

$j2a1 = json_decode($array[20],true)['fullname']; /*grab the value in the same line as the json_decode */
echo '<pre>';
echo "j2a1: ";
print_r($j2a1); /* Could have used an echo :) */

Will return:

Array
(
    [20] => {"shortname":"testvqweq","fullname":"test"}
    [21] => {"shortname":"bwqbdwqbwqeb","fullname":"qwbdwqbwq"}
    [22] => {"shortname":"wqdwqdwqdw","fullname":"dwqwqdwq"}
)
testvqweq
bwqbdwqbwqeb
wqdwqdwqdw
j2a1: test

I dumbed it down on purpose and did not use one lines to show how you turn the json in the array into an array and print the value you like from that one... and at the end I gave an example of a one liner without a loop.

You could simple access them with a foreach

foreach(array as arrayIndex)
{
   $shortName = arrayIndex['shortname'];
   $fullName= arrayIndex['shortname'];
}

if you need to use the variables you will want to do that action within the foreach loop as well or alternatively you will want to store them outside the foreach loop.

GL.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM