PHP+JSON Display result with no key? - php

First of all, sorry because my english is bad.
Ive got a problem.
Requesting data from URL in JSON format and got something like:
array(1) { ["NICK_HERE"]=> array(5) { ["id"]=> int(123456789) ["name"]=> string(11) "NICK_HERE" ["class"]=> int(538) ["level"]=> int(97) ["online"]=> int(1420061059000) } }
And then, I want to display something from there, normally it would be $x['NICK_HERE']['id'], but because NICK_HERE will be changing, and because i can't use a variable in there, is there a way to bypass this?
For example something like $x[0]['id'] ?
Sort of choose first, no matter whats that?
Appreciate your help!
P.s. Happy New Year!

My advice (because I think it is the simplest is to use current(), but you can also use array_column()...
Code: (Demo)
$array=[
"NICK_HERE"=>["id"=>123456789,"name"=>"NICK_HERE","class"=>538,"level"=>97,"online"=>1420061059000]
];
echo current($array)['id'];
echo "\n";
echo array_column($array,'id')[0];
Output:
123456789
123456789
These methods assume that the subarray element id is guaranteed to exist. If it might not, you will need to check with isset() before trying to access -- to avoid a Notice.

Since you know the first array has one key name you can get the 0th key.
test.php
$x = array(
"NICK_HERE" => array(
"id" => 123456789,
"name" => "NICK_HERE",
"class" => 538,
"level" => 97,
"online" => 1420061059000
)
);
$name = array_keys($x)[0];
echo $x[$name]["id"];
?>
output:
php test.php
123456789%

Use foreach loop.
Suppose your array name is $array.
foreach($array as $i=>$a)
{
echo "index: ".$i." id:".$a['id']."<br>";
}
Suppose your json string name is $json. Then use this way
$array=$json_decode($json);
foreach($array as $i=>$a)
{
echo "index: ".$i." id:".$a->id."<br>";//here you will get it as object
}
Hope you got the idea.

Related

php single entry associative array

I get data from a .xlsx file, which I also put into an array(named $tableArray, I used PHPExcel for that). now i don't know how I can output even a single entry in my array.
I tried
$tableArray[1];
getting all the entries works with
var_dump($tableArray);
my code:
<?php
$excelReader = PHPExcel_IOFactory::createReaderForFile($fileName);
$excelReader->setReadDataOnly();
$excelObj = $excelReader->load($fileName);
$excelObj->getActiveSheet()->toArray();
$worksheetNames = $excelObj->getSheetNames($fileName);
$tableArray = array();
foreach($worksheetNames as $key => $sheetName){
$excelObj->setActiveSheetIndexByName($sheetName);
$tableArray[$sheetName] = $excelObj->getActiveSheet()->toArray();
}
var_dump($tableArray);
?>
Here's a few tips to help get you started.
If you want to see your array in a cleaner format on your browser, surround the var_dump() in a <pre> tag like so.
<?php
$myArray = [
"orange" => "foo",
"bar" => [
"test" => "more"
]
];
?>
<pre>
<?php var_dump($myArray); ?>
</pre>
This will help you understand your array structure better as it will be easier to read.
Accessing values in arrays is as easy as referencing the key. For example in the array above, if we want the value of orange, just echo $myArray["orange"];
If the value is another array, such as the key bar, and we want the value of test, we can just reference both keys in order echo $myArray["bar"]["test"];
You can use foreach() to loop through your array and perform action on each key => value pair.
<?php
$myArray = [
"orange" => "foo",
"bar" => [
"test" => "more"
]
];
foreach($myArray as $key => $value) {
var_dump($key);
var_dump($value);
}
If you're looking for more detailed information I'd recommend going through some of the courses on Code Academy. It will help you not only with this question, but others involving basic functionality of PHP.
Hope this helps!

php, json to specific string

By POST I get this JSON (can have more than 3 values in it)
{"preferences":["Theater","Opera","Danse"]}
Well, I need to get
array('Theater', 'Opera', 'Degustation')
json_decode doesn't work.
Do you have any ideas please?
Thank you by advance
Try adding the true parameter:
$jsonData = '{"preferences":["Theater","Opera","Danse"]}';
$arrayData = json_decode($jsonData, true );
var_dump($arrayData['preferences']);
The last line outputs the following:
array(3) {
[0]=>
string(7) "Theater"
[1]=>
string(5) "Opera"
[2]=>
string(5) "Danse"
}
Which is what you want. Good luck!
That JSON string is wrapped in an object (denoted by curly braces {}). json_decode will give you the wrapper object whose "preferences" property is the array you're looking for.
$wrapper = json_decode($json_string);
$array = $wrapper->preferences;
json_decode might also be unavailable if you're using and older version of php. In that case you should try a php json library.
You might have used the output of the json_decode() function as an associated array while you hadn't have told the function to provide an associated array for you, or vice versa!! However, the following will get you the array at the preferences index:
<?php
$decoded = json_decode('{"preferences":["Theater","Opera","Danse"]}', true); // <-- note the second parameter is true.
echo '<pre>';
print_r($decoded['preferences']); // output: Array ( [0] => Theater [1] => Opera [2] => Danse )
// ^^^^^^^^^^^^^^^^^^^^^^^
// Note the usage of the output of the function as an associated array :)
echo '</pre>';
?>

In PHP, how can I convert an Array (dictionary) inside String variable to Array structure?

I was looking for in Stack some solution to convert a string variable to an Array. The String variable contents this:
$myvar = 'array("a" => array("b1" => 1, "b2" => "something"), "c" => array("d1" => 1))';
I want to convert as:
$myarray = array(
"a" => array (
"b1" => 1,
"b2" => "something"
),
"c" => array("d1" => 1)
);
I was using json_decode after to convert my huge string to json, I used implode too ...
Using eval, I recieve next error:
Parse error: syntax error, unexpected '<' in tabletocreate.php(51) : eval()'d code on line 1
I used print_r($myvar);
The idea it is I have an model inside a file model.php it is only a dictionary, I read this file inside a string and after to convert again an array, I do it because I need to generate a new database from this data, and I have the model for each catalog I need products, offer, ... obiously each model will be different but with the same structure of array, I wrote in the example
SOLUTION
faintsignal resolved the solution in my case: eval("\$myarray = " . $myvar . ';');
Use eval() http://www.php.net/manual/en/function.eval.php
$myarray = eval($myvar)
But don't do this if you're getting the $myvar from outside your script. Also, there are much better methods to serialize and unserialize data in PHP. For instance see http://www.php.net/manual/en/function.serialize.php
If you're reading a .php file directly you have to deal with <?php and ?>. You can pre-parse the file before passing it to eval(). If your file is as simple as:
<?php (php_declarations_and_stuff ?>
You can just remove <?php and ?>, and the eval() the file.
Another option may be just use include against the file. See http://www.php.net/manual/en/function.include.php. In this case include will eval the file in the global scope. Also see that if your included file uses return, you can just retrieve this value directly (See Example #5 in the include reference):
return.php
<?php return 'Ok'; ?>
myfile.php
$val = include('return.php');
print $val;
Will print "Ok".
eval() will accomplish what you need, but as another poster here advided in his answer, you must use this function with great caution.
$myvar = 'array("a" => array("b1" => 1, "b2" => "something"), "c" => array("d1" => 1))';
eval("\$myarray = " . $myvar . ';');
var_dump($myarray);
outputs
array(2) {
["a"]=>
array(2) {
["b1"]=>
int(1)
["b2"]=>
string(9) "something"
}
["c"]=>
array(1) {
["d1"]=>
int(1)
}
}
Someone commented that eval is deprecated but I cannot find any info to support this. However, its use is discouraged, so you might consider it as a last resort when existing PHP functionality will not accomplish your task.

Cleaner way to echo multi dimension array

echo "{$line['text_1']}";
the above echo works fine ,however when it comes to 2d array, in my sublime, only {$line['text_2']} this part work fine. output error both sublime and browser
echo "$array_2d[{$line['text_1']}][{$line['text_2']}]";
any idea?
update
echo "$array_2d[$line['text_1']][$line['text_2']]";
using xampp, error Parse error: syntax error, unexpected '[', expecting ']' in C:\xampp\htdocs
and I'm just outputting a value from the mysql_fetch_assoc. I can do it in another way by echo '' however I'm trying to make my code easier for future editting and code copy paste
and yes I'm doing things like
echo "The price is $array_2d[$line['text_1']][$line['text_2']]"
with lots of html code in the double quote.
Why are you trying to output the array?
if it is for debugging purposes, you can just use the native php functions print_r() or var_dump()
You should be able to say
echo "item is {$array_2d[$line['text1']][$line['text2']]}";
to get to a subelement.
Of course, this is only really useful when it's not the only thing in the string. If you're only echoing the one value, you don't need the quotes, and things get simpler.
echo $array_2d[$line['text1']][$line['text2']];
this should work :
echo $array_2d[$line['text_1']][$line['text_2']];
When echoing variables, you don't have to use the quotes:
echo $array_2d[$line['text_1']][$line['text_2']];
If you do need to output something with that string, the concatentation operator can help you:
echo "Array: " . echo $array_2d[$line['text_1']][$line['text_2']];
You can use print_r() to echo the array.
e.g.:
print_r($array);
Output will be:
Array ( [test] => 1 [test2] => 2 [multi] => Array ( [multi] => 1 [multi2] => 2 ) )
Also you can use this to make it more readable in a HTML context:
echo '<pre>';
print_r($array);
echo '</pre>';
Output will be:
Array
(
[test] => 1
[test2] => 2
[multi] => Array
(
[multi] => 1
[multi2] => 2
)
)
You can use print_r() or var_dump() to echo an array.
The print_r() displays information about a variable in a way that's readable by humans whereas the var_dump() function displays structured information about variables/expressions including its type and value.
$array = 'YOUR ARRAY';
echo "<pre>";
print_r($array);
echo "</pre>";
or
$array = 'YOUR ARRAY';
var_dump($array);
Example variations
I'm wondering why you would try using the $line array as a key to access data in $array_2d.
Anyway, try this:
echo($line['text_1'].'<br>');
this:
echo($array_2d['text_1']['text_2'].'<br>');
and finally this (based on your "the $line array provides the keys for the $array_2d" array example)
$key_a = $line['text_1'];
$key_b = $line['text_2'];
echo($array_2d[$key_a][$key_b].'<br>');
Which can also be written shorter like this:
echo($array_2d[$line['text_1']][$line['text_2']].'<br>');
Verifying/Dumping the array contents
To verify if your arrays hold the data you expect, do not use print_r. Do use var_dump instead as it will return more information you can use to check on any issues you think you might be having.
Example:
echo('<pre>');
var_dump($array_2d);
echo('</pre>');
Differences between var_dump and print_r
The var_dump function displays structured information of a variable (or expression), including its type and value. Arrays are explored recursively with values indented to show structure. var_dump also shows which array values and object properties are references.
print_r on the other hand displays information about a variable in a readable way and array values will be presented in a format that shows keys and elements. But you'll miss out on the details var_dump provides.
Example:
$array = array('test', 1, array('two', 'more'));
output of print_r:
Array
(
[0] => test
[1] => 1
[2] => Array
(
[0] => two
[1] => more
)
)
output of var_dump:
array(3) {
[0]=> string(4) "test"
[1]=> int(1)
[2]=> array(2)
{
[0]=> string(3) "two"
[1]=> string(4) "more"
}
}

array_key_exists returning false when array clearly has key

I'm doing some content importing using the node import module in drupal. My problem is that I'm getting errors on data that looks like it should be working smoothly. This is the code at issue:
if (count($allowed_values) && !array_key_exists($item['value'], $allowed_values)) { //$allowed_values[$item['value']] == NULL) {
print "||||" . $item['value'] . "||||";
print_r($allowed_values);
And this is a sample of what is printing:
||||1||||Array ( [0] => no [1] => Zicam® Cold Remedy Nasal Gel Spray Single Hole Actuator (“Jet”) ) ||||1||||Array ( [0] => No [1] => Yes )
It looks to me like it's saying that "1" is not in the array, when printing the way "1" is clearly visible. If I replace the existing module code with the commented out check, no error is thrown.
Your code is not complete and i cannot reproduce the error.
Allow me to adjust your example:
<?
$item = array('value' => 1);
$allowed_values = array(0 => 'no',1 => 'yes');
echo "needle:";
var_dump($item['value']);
echo "haystack:";
var_dump($allowed_values);
if (count($allowed_values) && !array_key_exists($item['value'], $allowed_values)) {
echo "needle hast not been found or haystack is empty\n";
} else {
echo "needle has been found\n";
}
gives the desired output:
needle:int(1)
haystack:array(2) {
[0]=>
string(2) "no"
[1]=>
string(3) "yes"
}
needle has been found
PHP also works when you assign the needle a string and not an integer. It is some sort of lossy type conversion that can be really convenient but also a pain in the ass. Often you dont know whats going on and errors are caused.
But still. I bet you have something wrong with your variable types.
You should dump them and see what is really in there.

Categories