php single entry associative array - php

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!

Related

convert numerically indexed associative-array in PHP, to valid JavaScript Object via JSON

Let's say you have a numerically indexed array that looks like this (obtained via RedBeanPHP's find operation):
[
[33=>["name"=>"John", "age"=25]],
[55=>["name"="Jane", "age"=23]]
]
where 33 and 55 are id's of each of the 2 "beans" (basically associative-arrays).
And you want to convert the array to JSON so you can send it to a JavaScript client and use the data there as a JavaScript Object.
But you can't simply JSON_encode this because you'll end up with numerical keys in a JavaScript Object, and JavaScript doesn't like that.
What strategy can you use to convert this array to a JavaScript Object via JSON so that all the data (including id of each bean) is available at the JavaScript end? (To the RedBeanPHP folks out there: I'm hoping there's a native RedBeanPHP way to do this that I haven't found yet.)
One option is using array_map to loop thru the array. Use array_values to get all the values from the array and indexes the array numerically.
$arr = [
[33=>["name"=>"John", "age"=>25]],
[55=>["name"=>"Jane", "age"=>23]]
];
$result = array_map(function($o){
return array_values($o)[0];
}, $arr);
echo json_encode( $result );
This will result as:
[{"name":"John","age":25},{"name":"Jane","age":23}]
Simple. You should try this. First iterate through the outer array and inside that get the key i.e id of the data. Add id to other values and push that array into resultant one.
$result = array();
$arr = [[33=>["name"=>"John", "age"=>25]],[55=>["name"=>"Jane", "age"=>23]]];
foreach ($arr as $ar) {
foreach ($ar as $key => $value) {
$value['id'] = $key;
array_push($result, $value);
}
}
echo json_encode($result);
Output :-
[{"name":"John","age":25,"id":33},{"name":"Jane","age":23,"id":55}]
For your associative array:
$array = array(33 => array("name" => "John", "age" => 25), 55 => array("name" => "Jane", "age" => 23));
PHP json_encode function:
$good_json = json_encode($array, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_NUMERIC_CHECK);
Produces JSON for JavaScript object (string "name" : value pair):
{"33":{"name":"John","age":25},"55":{"name":"Jane","age":23}}

MySQL JSON strings with PHP. fixing commas

I'm creating this JSON thingy and I need to remove the last comma from it. (yes I know I could do a simple way instead of making the json myself, but I need it to be like this {"1":0,"2":4,"3":1.5}) So how can I do it? (And yes I have a working way in the code but it doesent display it like I need it.)
<?php
require 'dbConnect.script.php';
$query="SELECT * FROM `trash`";
if($is_query_run=mysql_query($query)){
print "{";
while($query_execute=$query_execute=mysql_fetch_assoc($is_query_run)){
echo '<tr><td>"'.$query_execute['id'].'"</td>:<td>'.$query_execute['weight'].',</td></tr>';
//$rows = array();
//$rows[] = $query_execute;
//print json_encode($rows);
}
print "}";
}
else{
echo "query notexecuted";
}
?>
In your example, you can simply create an array:
$array = ["1" => 0, "2" => 4, "3" => 1.5];
$json = json_encode($array);
Since this array doesn't start with a zero (which indexed arrays does), this would give you your desired result.
If you want to start with a zero, and still get an object back:
$array = ["0" => 2, "1" => 0, "2" => 4, "3" => 1.5];
you can use the option JSON_FORCE_OBJECT as a second parameter, like this:
$array = ["0" => 2, "1" => 0, "2" => 4, "3" => 1.5];
$json = json_encode($array, JSON_FORCE_OBJECT);
This will give you:
{
"0": 2,
"1": 0,
"2": 4,
"3": 1.5
}
Read more here: http://php.net/manual/en/function.json-encode.php
It's seldom a good idea to build your own encoders/decoders for things like this. It usually gets quite complicated pretty quick, and you will spend most of your time straighten out bugs and get stuck on edge cases. It's better to read up on the native functions. They have been tried and tested for years, and are often much better in regards of performance.
Whilst I concur json_encode is the nicest solution for producing JSON. To produce a nice comma separated output you could use the implode function.
Set-up your elements in an array, so for example:
$data = array('"1":0', '"2":4', '"3":1.5');
Then use implode like this
$output = implode(',', $data);
Which will give you an output of the data elements in the array as a comma separated list
if($is_query_run=mysql_query($query)){ //Here you execute the query
while($query_execute=$query_execute=mysql_fetch_assoc($is_query_run)){ //Here you get one row from execution result
$rows = array(); //You create array into $rows, what was in $rows before will be wiped
$rows[] = $query_execute; // You insert one row you just fetch from result to $rows
print json_encode($rows); // You encode $rows (which always has only one element as you wipe it every iteration)
}
}
So, create array before loop, and encode that array after loop, adding elements to array inside a loop is ok.
-Mr_KoKa #LinusTechTips.com

Php array_rand() printing variable name

I have an array that is filled with different sayings and am trying to output a random one of the sayings. My program prints out the random saying, but sometimes it prints out the variable name that is assigned to the saying instead of the actual saying and I am not sure why.
$foo=Array('saying1', 'saying2', 'saying3');
$foo['saying1'] = "Hello.";
$foo['saying2'] = "World.";
$foo['saying3'] = "Goodbye.";
echo $foo[array_rand($foo)];
So for example it will print World as it should, but other times it will print saying2. Not sure what I am doing wrong.
Drop the values at the start. Change the first line to just:
$foo = array();
What you did was put values 'saying1' and such in the array. You don't want those values in there. You can also drop the index values with:
$foo[] = 'Hello.';
$foo[] = 'World.';
That simplifies your work.
You declared your array in the wrong way on the first line.
If you want to use your array as an associative Array:
$foo=Array('saying1' => array (), 'saying2' => array(), 'saying3' => array());
Or you can go for the not associative style given by Kainaw.
Edit: Calling this on the not associative array:
echo("<pre>"); print_r($foo); echo("</pre>");
Has as output:
Array
(
[0] => saying1
[1] => saying2
[2] => saying3
[saying1] => Hello.
[saying2] => World.
[saying3] => Goodbye.
)
Building on what #Answers_Seeker has said, to get your code to work the way you expect it, you'd have to re-declare and initialise your array using one of the methods below:
$foo=array('saying1'=>'Hello.', 'saying2'=>'World.', 'saying3'=>'Goodbye.');
OR this:
$foo=array();
$foo['saying1'] = "Hello.";
$foo['saying2'] = "World.";
$foo['saying3'] = "Goodbye.";
Then, to print the contents randomly:
echo $foo[array_rand($foo)];

Multidimensional Array for JSON structure in PHP

Recently I had some experience with converting mysql query results into json for a quiz system. Query results contain set of questions and related anwsers to them. The implemented procedure aims to put those questions and answers into multidimensional array and then convert it into json to build quiz db. I've ready to use JS procedure (quiz module) that works with below mentioned JSON structure. But to build this structure I'm stuck with the following php procedure:
Code in PHP:
$query = "SELECT s1.question, s2.answers, s2.correct
FROM `questions` s1, `answers` s2
WHERE s1.id=s2.questionid AND s1.courseid=".$_POST['courseid']."";
$result = mysqli_query($mysqli, $query) or die ("<b>Select failed:</b> ".mysqli_error($mysqli));
$final_quiz = array();
$final_quiz['introduction'] = "Introduction text goes here";
while ($rows = mysqli_fetch_assoc($result_quiz)) {
$final_quiz['questions']['question'] = $rows['question'];
$final_quiz['questions']['question']['answers'] = array($rows['answers'], "correct"=> $rows['correct']);
}
// convert to JSON
$json = json_encode($final_quiz);
echo $json;
Expected JSON Output:
{
"introduction":"Some introductory text here",
"questions":[
{
"question":"Question number one here?",
"answers":["some incorrect answer", "a correct answer", "another incorrect answer"],
"correct":1}, // indicates an array key that is relates to keys in "answers"
...
]
}
How to organize multidimensional array in order to get above mentioned json structure? Any help would be appreciated.
UPDATES
The values in correct keys are indexes of the answers keys, i.e. if we have "correct":1 that would mean second value of answers key. Correct values for answers that come from MySQL are boolean (TRUE/FALSE). So, before putting all answers in answers_array_key as a set of answers one should remember newly assigned index array for the answer with TRUE value put that index array in correct_array_key as value. An example:
....
"answers":[0:"some incorrect answer", 1:"a correct answer", 2:"another incorrect answer"],
"correct":1}, // this is correct answer key
....
Hope that will that will explain the idea of desired json sturcture mentioned above.
I think this will produce the result you want.
while ($rows = mysqli_fetch_assoc($result_quiz)) {
$final_quiz['questions'][]= array(
'question' => $rows['question'],
'answers' => array($rows['answers']),
'correct'=> $rows['correct']
);
}
In your code, you are overwriting a single element of that array instead of appending the other questions
You can try to use the php json_encode command. (link on php.net -> http://php.net/manual/it/function.json-encode.php)
The link show some example of array structure. On php.net it says it works with each type of structure (not resources).
Edit: as i see you already use this command, but how is the actual output? How much is different from your desired one?
I believe this will solve it for you (I've used an array to test, I hope I got the question right).
You will need to change the foreach loop back to your while loop.
I might have used a bit of different naming, you might need to change a thing or 2 to match your exact names:
<?php
$tmp = array (
array("question"=> "this is a q", "answer"=>"incorrect", "correct" => false),
array("question"=> "this is a q", "answer"=>"incorrect1", "correct" => false),
array("question"=> "q1", "answer"=>"correct", "correct" => true),
array("question"=> "q1", "answer"=>"incorrect", "correct" => false),
array("question"=> "q1", "answer"=>"incorrect1", "correct" => false),
array("question"=> "this is a q", "answer"=>"incorrect1", "correct" => false),
array("question"=> "this is a q", "answer"=>"incorrect2", "correct" => false),
array("question"=> "this is a q", "answer"=>"correct", "correct" => true),
array("question"=> "this is a q", "answer"=>"incorrect3", "correct" => false)
);
$QAndA = array();
foreach ($tmp as $t){
if (!isset($QAndA[$t['question']]['answers']))
$QAndA[$t['question']]['answers'] = array();
$QAndA[$t['question']]['answers'][] = $t['answer'];
if ($t['correct'])
$QAndA[$t['question']]['correct'] = count($QAndA[$t['question']]['answers']) -1;
}
foreach ($QAndA as $q => $data){
$final_quiz['questions'][] = (object)array("question" => $q,
"answers" => $data['answers'],
"correct" => $data['correct']);
}
$json = json_encode($final_quiz);
echo $json;
?>
Result:
{
"questions": [{
"question": "this is a q",
"answers": ["incorrect", "incorrect1", "incorrect1", "incorrect2", "correct", "incorrect3"],
"correct": 4
}, {
"question": "q1",
"answers": ["correct", "incorrect", "incorrect1"],
"correct": 0
}]
}
I do want to apologize for the naming conventions here and the somewhat brute attitude this code presents, but it is very late here;
Add one counter $i and try the below code:
$i = 0;
while ($rows = mysqli_fetch_assoc($result_quiz)) {
$final_quiz['questions'][$i] = array(
'question' => $rows['question'],
//'answers' => $rows['answers'], UPDATE THIS LINE
'answers' => array(
'1' => $rows['answers'][1],
'2' => $rows['answers'][2],
'3' => $rows['answers'][3])
// Why I started from index one? if index is consecutive from 0 to n
// will remove the index in JSON, so start indexing from 1 and make some changes in ur code
'correct' => $rows['correct']
);
$i++;
}
this will work

Add an array elements into PHP/ Insert variable with value with Array_push

I am able to parse data from youtube gdata. For example:
$json_output = json_decode($json,TRUE);
foreach ( $json_output['data']['items'] as $data ){
echo $data['content'][1]
. '</br>'
. $data['title'];
These give me rtsp url and title. Now suppose I want some other elements to add to the output (I don't possess knowledge of php, so I don't know the terms actually). What I want, that the output should have an another variable, let's take 'Boys'. This variable will have index key values same as youtube gdata and will be as follows:
Boys="You", "Me", "He", "Doggy",.....nth value.
My above code gives two values each time-url and title. Now I want the 3rd value which will be added to that from 'Boys'.
I tried Array_push as follows but it adds as an extra element and not as a variable like 'title' or 'content'.
$Boys= array('demi', 'ffe', 'erere');
array_push($json_output['data']['items'], $Boys );
How to properly insert Boys as variable? is there other methods like merge etc. to do it?
Again, since I am not a coder, please pardon my words!
Let's say you have 2 arrays with same keys, then you can do array_merge_recursive() to merge them together.
Here is a working example,
$a = [ 'boys' => ['play', 'sing']];
$b = ['boys' => 'fight'];
$merged = array_merge_recursive($a, $b);
print_r($merged);

Categories