two-dimension array after fgets? - php

I´m learning to work with files in php, first i made this function for writing to the file, it´s quite simple:
function zapis_do_suboru($zapisovany_subor, $obsah_suboru)
{
$pracovny_subor = fopen($zapisovany_subor,"w") or die("Chyba pri otvarani suboru");
fwrite($pracovny_subor, $obsah_suboru) or die("Nejde zapisovat do suboru");
fclose($pracovny_subor);
echo "Zapis $zapisovany_subor prebehol uspesne.";
}
Then I made function for reading from the file, but I was little stuck here, because my book is explaining how to read just one row, but then i googled little bit and found some solution and made this function for reading from file:
function citanie_zo_suboru($citany_subor)
{
$pracovny_subor = fopen($citany_subor,"r") or die("Chyba pri otvarani suboru");
$j = 0;
while(!feof($pracovny_subor))
{
$pole[$j] = array(fgets($pracovny_subor, 4096));
$j++;
}
fclose($pracovny_subor);
return $pole;
}
Then i wanted to test it, so i create two variables:
$subor = "textsubor.txt";
$text = <<<_END
Riadok1 blabla
Riadok2 blabla
Riadok3 meno suboru: $subor
_END;
And this calling of functions:
zapis_do_suboru($subor, $text);
echo "<br />";
foreach (citanie_zo_suboru($subor) as $index =>$popis)
echo $popis."<br />";
But the problem is, that function citanie_zo_suboru is creating two-dimension array, so the output was only "array array array array". With print_r and little bit of trying i found out, that when i change:
foreach (citanie_zo_suboru($subor) as $index =>$popis)
echo $popis."<br />";
to:
foreach (citanie_zo_suboru($subor) as $index =>$popis)
echo $popis[0]."<br />";
it's doing exactly what i wanted. Can someone tell me why my function is creating two-dimension and not just classic one-dimension array? I would be really grateful if you could. Thanks

You are storing array in array key:
$pole[$j] = array(fgets($pracovny_subor, 4096));
So, $pole[0] should further contain array.

To simply write a file you can use file_put_contens() : http://php.net/manual/fr/function.file-put-contents.php
To read a file you have the same file_get_contents() : http://php.net/manual/en/function.file-get-contents.php
To read a file and store each line as value in an array use file() : http://www.php.net/manual/en/function.file.php
I hope this 3 function can help you in your current issue.

Related

Echo an Array and make the content look pretty on the page

I am trying to echo out my array on each line, not bunched together.
I have tried <br />, this only show's on the front end, but when you look at HTML code. Its still clumped together.
$arrays = [];
$arrays[] = "Good";
$arrays[] = "Bad";
foreach ($arrays as $array){
echo $array;
}
Result:
GoodBad
Want Result:
Good
Bad
Short of using print_r, to quickly get your desired result, just make this small change:
echo $array."\n";
Make sure it's double-quotes and it will add a new line.
(That would do what "<br />" does on HTML)
Try using print_r($arrays). docs here.
Try echo "<pre>; var_dump($arrays); echo "</pre>;

PHP array unique on multi dimensional array/object

I've been trying for a while. I have tried several things to fix this, but I just can't get it to work.
My code:
<?php
if (is_array($row))
{
foreach ($row as $data) {
echo array_unique($data->username);
}
}
?>
It gives me the following error
Message: array_unique() expects parameter 1 to be array, string given
I have no idea what is going on with this. I have even tried placing the array_unique in the $row.
So like:
<?php
if (is_array($row))
{
foreach (array_unique($row) as $data) {
echo $data->username;
}
}
?>
But this gives me another error:
Object of class stdClass could not be converted to string
I have no idea what's going on. I have searched for hours but haven't found anything on here. Any help is greatly appreciated. Thanks.
You can't use array_unique on multi-dimensional arrays when you're looking inside the depth. Its works on flat one, and certainly won't work on strings. An alternative is to create another container for that and use usernames as keys, then you'll get unique ones.
Since you haven't shown the array/object structure, here a little bit on an idea on the comment I gave above:
$container = array();
foreach($row as $data) {
if(!isset($container[$data->username])) {
$container[$data->username] = $data;
}
}
// $container = array_values($container); // optional simple reindex

PHP Array during echo

I have an assignment to do but am having trouble understanding the given psuedocode :/
<?php
$bucket = new array();
print $bucket->addrocks('Rock1')->addrocks('rock2')-
>addrocks('Rock3');
echo "<h1>My Bucket</h1>";
echo "<ul>";
foreach($bucket as $rock){
echo "<li>". $rock ."</li>";
}
echo "</ul>";
?>
Now my trouble starts with understanding how they want me to construct the array after the "print" call? i am not looking for a direct answer to this just maybe a tutorial link or a finger in the right direction
Thank you in advance
In PHP, new is only used for instantiating objects Furthermore, array is a reserved word in PHP, so name your class something else. To instantiate an array in PHP you do this:
$my_array = array();
Now to add items to the array you would do this:
$my_array[] = "Rock 1";
$my_array[] = "Rock 2";
$my_array[] = "Rock 3";
To traverse the array you can use any type of loop, but usually you would just use a foreach loop.
For example:
foreach($my_array as $key => $value) {
echo $value . "<br />";
}
The problem lies in the array construction. This is how one constructs an array in PHP:
one by one:
$bucket = array();
$bucket[] = "Rock1";
$bucket[] = "Rock2";
$bucket[] = "Rock3";
All at once:
$bucket = array("Rock1","Rock2","Rock3");
The documentation: http://php.net/manual/en/language.types.array.php
Well unlikely but may be the array is not an construct but an class in your pseudocode. My assumptions depend on the use of new keyword and the user of -> and addrocks which looks like a method.
So, create a class called array (stupid I know) and get going.
However the user of foreach($bucket) also shows that it expects $bucket to be array. So decide wisely :)
May be use a magic method called __toString() inside the class and return back the array.

How to reference a item in an array numerically when it has been created as an associative array

I am using PHP 5.3.6
I have the following code below. Everything works fine except for the last line which attempts to to return a value based on the position in the array as opposed to the associative name. Can anyone explain why this takes place and how I can build the array so that I can reference an item either by the associative name or position number?
Thanks.
<?php
class myObject {
var $Property;
function myObject($property) {
$this->Property = $property;
}
}
$ListOfObjects['form_a'] = new myObject(1);
$ListOfObjects['form_b'] = new myObject(2);
$ListOfObjects['form_c'] = new myObject(3);
$ListOfObjects['form_d'] = new myObject(4);
echo "<pre>";
print_r($ListOfObjects);
echo "</pre>";
echo "<hr />";
foreach ($ListOfObjects as $key => $val) {
echo "<li>" . $ListOfObjects[$key]->Property . "</li>";
}
echo "<hr />";
echo "<li>" . $ListOfObjects['form_a']->Property . "</li>"; // Works ok.
//Edit: ------------------------------------------------------------
//Edit: Everything above is for context only
//Edit: I'm only interested in the line below and why it does not work
//Edit: ------------------------------------------------------------
echo "<li>" . $ListOfObjects[0]->Property . "</li>"; //Does not work.
?>
function value_from_index($a,$k){
return array_slice($a,$k,1);
}
If you just want the first/last element of an array, try end($array) for the last item without destroying it and reset($array) to get the first.
Don't use reset and end if you're looping through an array as Flambino notes, this indeed results in some unexpected behaviour.
For anything inbetween you'll need to use array_slice()
Not the nicest way of doing it, but effektive and readable:
$i = 0;
$last = count($ListOfObjects);
foreach($ListOfObjects as $obj) {
if($i == 0) {
//do something with first object
$obj->property;
else if ($i == ($last-1)) {
//do something with last object
$obj->property;
}
}
PHP arrays aren't like arrays you know from most other programming languages, they are more like ordered hash tables / ordered dictionaries - they allow for access by named index and retain order when new items are added. If you want to allow access with numeric indices to such an array you have to define it that way or use one of roundabout ways given in other answers.
In your case you can use a single line of code to allow access by index:
$ListOfObjects += array_values($ListOfObjects);
This will extend your array with the same one but with numeric indices. As objects are always passed by reference, you can access the same object by writing $ListOfObjects['form_b'] and $ListOfObjects[1].

a very hard result to foreach in php

$content is an arry. when i print_r($content) the result is too long. now i
echo $fenlei=$content['body']['#object']->field_fenlei['zh-hans'][0]['taxonomy_term']->name;
the result of $fenlei is java. but there maybe many values of $fenlei. eg:
$content['body']['#object']->field_fenlei['zh-hans'][0]['taxonomy_term']->name;
$content['body']['#object']->field_fenlei['zh-hans'][1]['taxonomy_term']->name;
$content['body']['#object']->field_fenlei['zh-hans'][2]['taxonomy_term']->name;
......
how to loop out the
$content['body']['#object']->field_fenlei['zh-hans'][1]['taxonomy_term']->name;
$content['body']['#object']->field_fenlei['zh-hans'][2]['taxonomy_term']->name;
value. it too hard for me. :)
You can store the common code and foreach next:
$common = $content['body']['#object']->field_fenlei['zh-hans'];
foreach($common as $key => $value){
echo "{$key}: " . $value['taxonomy_term']->name;
}
If you want to print out large arrays that are difficult to read you can try:
echo '<pre>'.print_r($array, true).'</pre>';
It makes arrays a little more pretty.

Categories