How to make variable that's in an array format into an array - php

This is probably a simple question, but how do I take a variable like the following and make it into an array.
$hot = "It","is","hot","outside";
Doing the following doesn't work:
$newhot = array($hot);
I'm actually calling an API that looks like:
[["P0010001","NAME","state","zip code tabulation area"],
["68191","ZCTA5 99301","53","99301"]]
What I need is the population on the second line (first quotes).
Doing the following gives me "68191","ZCTA5 99301","53","99301"
$splitContent = implode("\n",array_slice(explode("\n",$populate),1,2));
$newContent = str_replace(']','',$splitContent);
$newContent = str_replace('[','',$newContent);

This
$hot = "It","is","hot","outside";
will generate error in PHP. But let's say you have the following retrieved from the API:
$str='[["P0010001","NAME","state","zip code tabulation area"],["68191","ZCTA5 99301","53","99301"]]';
then, if you run this line:
$myArray = json_decode($str);
and then
echo "<pre>";
print_r($myArray);
echo"</pre>";
you can have this result:
Array
(
[0] => Array
(
[0] => P0010001
[1] => NAME
[2] => state
[3] => zip code tabulation area
)
[1] => Array
(
[0] => 68191
[1] => ZCTA5 99301
[2] => 53
[3] => 99301
)
)
Second line of data will be stored in
$myArray[1]

Defining an array is something like...
$hot = array("It","is","hot","outside");
Re: Your Api call...
$ApiResponse = '[["P0010001","NAME","state","zip code tabulation area"],["68191","ZCTA5 99301","53","99301"]]';
$Response = json_decode($ApiResponse);
$Data = $Response[1];
Specifically, the api is returning a list of lists. We're taking the 2nd (0-indexed) list. $Data will now be the same as if you'd declared...
$Data = array("68191","ZCTA5 99301","53","99301");
Edit: Tested Code...
$Key = '[Your Key]';
$ApiResponse = file_get_contents("http://api.census.gov/data/2010/sf1?key={$Key}&get=P0010001,NAME&for=zip+code+tabulation+area:99301&in=state:53");
print "Raw: " . print_r($ApiResponse, true) . "<hr/>";
$Response = json_decode($ApiResponse);
$Data = $Response[1];
print "Extracted Data: " . print_r($Data, true) . "<br/>";
print "First bit of data: {$Data[0]}.<br/>";
print "Second bit of data: {$Data[1]}.<br/>";

Related

How to access this array containing objects in Laravel

The table filed name is called metadata, and within the metadata contained an array of objects such as
[{"title":"Type","value":"Hard Drive (HDD)"},{"title":"Condition","value":"Used"}]
How do I access it using PHP/Laravel. Any help is appreciated. Thanks
You need to decode it, with json_decode() php function :
$x = '[{"title":"Type","value":"Hard Drive (HDD)"},{"title":"Condition","value":"Used"}]';
$y = json_decode($x, true);
print_r($y);
Output :
Array
(
[0] => Array
(
[title] => Type
[value] => Hard Drive (HDD)
)
[1] => Array
(
[title] => Condition
[value] => Used
)
)
Now you can access the value with foreach loop as :
foreach($y as $key => $val) {
echo "Title : " . $val['title'] . $val['value'] ;
}
Above code tested here
The code you have posted is a JSON string. So you first have to decode it to a PHP array with the function json_decode. After that you can access it easily.
Try this out:
$json = '[{"title":"Type","value":"Hard Drive (HDD)"},{"title":"Condition","value":"Used"}]';
$assoc_array = json_decode($json, true); // second parameter is true to get an associative array
echo $assoc_array[0]['title'];

Custom While in json array

Its My PHP Code:
$res_media=mysql_query("SELECT * FROM mv_media");
$media = array();
while($resualt_media = mysql_fetch_assoc($res_media)) {
$media[]= $resualt_media['title'];
}
echo $media;
And Its My output:
["Test","Test","Test","Test","Test"]
I want Change it to this format :
["Test"],["Test"],["Test"],["Test"],["Test"]
I changed My Code to this code :
$res_media=mysql_query("SELECT * FROM mv_media");
$media = array();
while($resualt_media = mysql_fetch_assoc($res_media)) {
$media[]= [$resualt_media['title']];
}
echo $media;
Now My OutPut :
[["Test","Test","Test","Test","Test"]]
But I need This custom output:
[["Test"],["Test"],["Test"],["Test"],["Test"],["ItsMyCustomChild"]]
I want add Custom Child with out database!
You can change $media[] = [<value>] to $media[][] = <value> and it will work, because then you'll create a new array inside an array.
I would suggest this approach:
<?php
$input = json_decode('["Test","Test","Test","Test","Test"]');
$output = [];
array_walk($input, function($element) use (&$output) {
$output[] = [$element];
});
var_dump(json_encode($output));
Alternatively this can be simplified to just:
<?php
$data = json_decode('["Test","Test","Test","Test","Test"]');
array_walk($data, function(&$element) {
$element = [$element];
});
var_dump(json_encode($data));
The created array structure obviously is:
Array
(
[0] => Array
(
[0] => Test
)
[1] => Array
(
[0] => Test
)
[2] => Array
(
[0] => Test
)
[3] => Array
(
[0] => Test
)
[4] => Array
(
[0] => Test
)
)
Which, if you again json_encode() it, results in the desired format:
string(46) "[["Test"],["Test"],["Test"],["Test"],["Test"]]"
The specific issue you are actually dealing with is not so much the creation of the desired structure, but that you are trying to modify the JSON string instead of the actual array you want to work with. That is why a call to json_decode() is used initially.
$res_media=mysql_query("SELECT * FROM mv_media");
$media = array();
while($resualt_media = mysql_fetch_assoc($res_media)) {
array_push($media,array($resualt_media['title']));
}
print_r $media;
You just need to change below line. and you will get your desired result.
$media[][]= $resualt_media['title'];
if you want to see what you get . you need to add json_encode() after the while.
like below
echo json_encode($media);

API response in Laravel decode issue

i have the following route:
Route::get('/verifica-dominio', function() {
$dom = Input::get('dominio');
$dominio = explode('.', Input::get('dominio'));
$name= $dominio[0];
$tld = $dominio[1];
$url = 'https://api.cloudns.net/domains/check-available.json?auth-id=1243&auth-password=KNK-dn5.&name=' . $name . '&tld[]=' . $tld;
$json = file_get_contents($url, true, stream_context_create(['socket' => ['bindto' => '0:0']]));
$j = json_decode($json);
return var_dump($j);
});
it return this object
object(stdClass)#1023 (1) { ["provola.com"]=> object(stdClass)#1024 (1) { ["status"]=> int(0) } }
how i can got status=1 in my code?
you can use json_decode() , its takes a JSON encoded string and converts it into a PHP variable.
$j = json_decode($json, TRUE);
print_r($j);
and your php section you can use php array to you can process data
this is common format
<?php
$json = '{"a":1,"b":2,"c":3,"d":4,"e":5}';
echo "<pre>";
print_r(json_decode($json, true));
?>
and this output is :
Array
(
[a] => 1
[b] => 2
[c] => 3
[d] => 4
[e] => 5
)
for more information
http://php.net/manual/en/function.json-decode.php
Pass TRUE as the second argument to json_decode() to make it decode the JSON to arrays and not to objects:
$j = json_decode($json, TRUE);
print_r($j);
Output:
Array
(
[provola.com] => Array
(
[status] => 0
)
)
Now everything became much clearer and easier to handle. $j['pravola.com']['status'] is the value you are looking for.
If it is not more clear then read about PHP arrays and insist on the "Accessing array elements with square bracket syntax" section.
I guess the key 'pravola.com' is what you pass to the remote API in argument tld. If this is the case then you can use $j[$tld]['status'] to get the data you need.

How can I extract value from an xml

I'm new to PHP. I'm trying to get the data out of the below XML. Now, in my code $data->Address contains value of the below code i.e:
$data->Address = "<tolist></tolist>
<cclist>
<cc>
<contactpersonname>niraj</contactpersonname>
<name>niraj</name>
<email>stgh#gmail.com</email>
<number>+91.3212365212</number>
<prefix>Ms.</prefix>
<contactpersonprefix>Ms.</contactpersonprefix>
</cc>
<cc>
<contactpersonname>fdg</contactpersonname>
<name>admin</name>
<email>admin12#gmail.com</email>
<number>+91.4554343234</number>
<prefix>Mr.</prefix>
<contactpersonprefix>Mr.</contactpersonprefix>
</cc>
</cclist>";
Now I want to extract the <contactpersonname> tag and print it. How can I do this?
Since your XML is missing a tag that encompasses all others, you need to create on in order to get parsers to work properly:
<?php
$buffer = "<tolist></tolist>
<cclist>
<cc>
<contactpersonname>niraj</contactpersonname>
<name>niraj</name>
<email>stgh#gmail.com</email>
<number>+91.3212365212</number>
<prefix>Ms.</prefix>
<contactpersonprefix>Ms.</contactpersonprefix>
</cc>
<cc>
<contactpersonname>fdg</contactpersonname>
<name>admin</name>
<email>admin12#gmail.com</email>
<number>+91.4554343234</number>
<prefix>Mr.</prefix>
<contactpersonprefix>Mr.</contactpersonprefix>
</cc>
</cclist>";
// ***** wrap the whole thing in a <root> tag...
$xml = simplexml_load_string("<root>".$buffer."</root>");
$array = json_decode(json_encode((array) $xml), 1);
echo "<pre>";
print_r($array);
echo "</pre>";
?>
Result:
Array
(
[tolist] => Array
(
)
[cclist] => Array
(
[cc] => Array
(
[0] => Array
(
[contactpersonname] => niraj
[name] => niraj
[email] => stgh#gmail.com
[number] => +91.3212365212
[prefix] => Ms.
[contactpersonprefix] => Ms.
)
[1] => Array
(
[contactpersonname] => fdg
[name] => admin
[email] => admin12#gmail.com
[number] => +91.4554343234
[prefix] => Mr.
[contactpersonprefix] => Mr.
)
)
)
)
UPDATED
Now you can navigate down to where you want to go with
echo "<pre>";
$ccList = $array['cclist'];
$cc = $ccList['cc'];
$contacts = array();
foreach($cc as $i=>$val) {
$contacts[$i]=$val['contactpersonname'];
}
echo "first contact: " . $contacts[0] . "<br>";
echo "second contact: " . $contacts[1] ."<br>";
Result:
first contact: niraj
second contact: fdg
You can convert the XML to an array with the following code:
$xml = simplexml_load_string($buffer);
$array = json_decode(json_encode((array) $xml), 1);
Where $buffer is the xml string.
Then you can obtain the person name as follow:
$data->Address = $array['cclist']['cc']['contactpersonname'];
It's a quick and dirty method to convert the xml to an array, but it works.
Try this..
$xml = new SimpleXMLElement($string);
$results = $xml->xpath('cclist/cc/contactpersonname');
http://php.net/manual/en/simplexmlelement.xpath.php
$xml = simplexml_load_file("note.xml");
echo $xml->contactpersonname;
This requires you to load it form an xml file. If you already have the string in the code I'd recommend a regex. If you know the data won't ever be incorrect written!
$pattern = '#<contactpersonname>(.*?)</contactpersonname>#';
echo preg_match ($pattern, $data->Address);

PHP rewriting a json array (Undefined offset)

I'm taking some json, made by OpenLibrary.org, and remake a new array from the info.
Link to the OpenLibrary json
here is my PHP code to decode the json:
$barcode = "9781599953540";
function parseInfo($barcode) {
$url = "http://openlibrary.org/api/books?bibkeys=ISBN:" . $barcode . "&jscmd=data&format=json";
$contents = file_get_contents($url);
$json = json_decode($contents, true);
return $json;
}
the new array I'm trying to make looks something like this:
$newJsonArray = array($barcode, $isbn13, $isbn10, $openLibrary, $title, $subTitle, $publishData, $pagination, $author0, $author1, $author2, $author3, $imageLarge, $imageMedium, $imageSmall);
but when I try to get the ISBN_13 to save it to $isbn13, I get an error:
Notice: Undefined offset: 0 in ... on line 38
// Line 38
$isbn13 = $array[0]['identifiers']['isbn_13'];
And even if I try $array[1] ,[2], [3].... I get the same thing. What am I doning wrong here! O I know my Valuable names might not be the same, that's because they are in different functions.
Thanks for your help.
Your array is not indexed by integers, it is indexed by ISBN numbers:
Array
(
// This is the first level of array key!
[ISBN:9781599953540] => Array
(
[publishers] => Array
(
[0] => Array
(
[name] => Center Street
)
)
[pagination] => 376 p.
[subtitle] => the books of mortals
[title] => Forbidden
[url] => http://openlibrary.org/books/OL24997280M/Forbidden
[identifiers] => Array
(
[isbn_13] => Array
(
[0] => 9781599953540
)
[openlibrary] => Array
(
[0] => OL24997280M
)
So, you need to call it by the first ISBN, and the key isbn_13 is itself an array which you must access by element:
// Gets the first isbn_13 for this item:
$isbn13 = $array['ISBN:9781599953540']['identifiers']['isbn_13'][0];
Or if you need a loop over many of them:
foreach ($array as $isbn => $values) {
$current_isbn13 = $values['identifiers']['isbn_13'][0];
}
If you expect only one each time and must be able to get its key without knowing it ahead of time but don't want a loop, you can use array_keys():
// Get all ISBN keys:
$isbn_keys = array_keys($array);
// Pull the first one:
$your_item = $isbn_keys[0];
// And use it as your index to $array
$isbn13 = $array[$your_item]['identifiers']['isbn_13'][0];
If you have PHP 5.4, you can skip a step via array dereferencing!:
// PHP >= 5.4 only
$your_item = array_keys($array)[0];
$isbn13 = $array[$your_item]['identifiers']['isbn_13'][0];

Categories