I need to use a key from an array for a check.
The array comes from a PDO query like this
function getProject($proj_id) {
$database = new Database();
$database->query( "SELECT * FROM projects WHERE proj_id = '$proj_id' LIMIT 1" );
$project = $database->resultSet();
return $project;
}
Then I print the array which works like it should.
$project = getProject(1);
print_r($project);
Array ( [0] => Array ( [proj_id] => 73 [proj_name] => Cake )
But when I try to print a specific key from the array like this:
print_r($project['proj_name'];
Nothing gets printed on the screen. Why not?
You have two arrays:
Array ( [0] => Array ( [proj_id] => 73 [proj_name] => Cake )
^--this one ^--and this one
You need to do:
print_r($project[0]['proj_name']);
Probably the ideal situation would actually be to change it here:
function getProject($proj_id) {
$database = new Database();
$database->query( "SELECT * FROM projects WHERE proj_id = '$proj_id' LIMIT 1" );
$project = $database->resultSet();
return $project[0]; //<---added the [0] this line
}
since you know it will always return one
If you look carefully, you'll see that you have two arrays nested one inside the other. Try print_r($project[0]['proj_name'];
You're missing a close-paren ) at the end of your print_r call.
You're seeing nothing on the screen because this means the file cannot be parsed, and errors are being logged to a file rather than displayed on screen. See How do I get PHP errors to display? for how to fix that.
Related
I am trying to run a function that gets information from a DB and returns an array of the values, so I can then extract it on the page.
Inside the function, after my query I have the following code:
$example_array = array();
while ($row = mysql_fetch_assoc($query) {
$example_array[] = $row;
}
return $example_array;
And there ends my function. Outside of it, I have this:
extract($example_array);
And I would assume I could then directly echo any of the variables that were previously in $example_array, e.g. <?= $example_var ?> but they do not contain any data.
Running print_r($example_array); gives an array that looks like this:
Array ( [0] => Array ( [example_var] => Example String ) )
The start of that code makes me think my array is somehow "lost" inside another array's first ([0]) value, and as such is not extracting correctly.
Have I gone about adding data to that initial $example_array incorrectly?
When you do $example_array[] = $row;, you assign the current row to a new index of $example_array. If you want to access it like $example_array['row_name'], you'd have to assign it like this:
$example_array = $row;
But when you do this, $example_array will be overwritten until it has reached the last row (which means that $example_array will always contain the last row from the query). If you just want the first row, you can do this and skip the whole while loop:
$example_array = mysql_fetch_assoc($query);
Maybe :
$example_array = array();
while ($row = mysql_fetch_assoc($query) {
array_push($example_array, $row['exemple_var']);
}
return $example_array;
The issue is that mysql_fetch_array would have meant $row['row_name'] was valid.
As you added $row to the array $example_array, you now need to access it via it's array id too, such as;
$example_array[0]['row_name'], $example_array[1]['row_name'] etc.
What exactly are you trying to achieve? May be easier to offer assistance if we know.
This question already has answers here:
in_array() and multidimensional array
(24 answers)
Closed 8 years ago.
I'm a newb and I got a problem with in_array...
So this is my array $allUsers (received by a SQL-Query for Usernames)
Array
(
[0] => Array
(
[name] => test
)
[1] => Array
(
[name] => test2
)
[2] => Array
(
[name] => admin
)
[3] => Array
(
[name] => kingChräbi
)
Now If a new member wants to register, I want to check in this array if it's already existent:
if(!in_array($username,$allUsers)){....
eventhough it is to when $username is NOT in $allUsers do .... it's just skipping to else also if the user is existing :(
$username is set before with
$username = $_POST['name'];
and working as it should (i can echo it without a problem, is exactly test or test2 without whitespace or anything)
I really looked around alot, but I can't find anything like my problem here... Could you please help me?
Thanks
although question itself is quite silly, as you have to realize what array you are working with, the quick solution, based on PDO tag, would be as follows: instead of fetchAll() use fetchAll(PDO::FETCH_COLUMN)
Or, rather you need to learn SQL as well, and find users not by means of selecting them ALL from database which makes no sense, but by asking a database to find a user for you
$stm = $pdo->prepare("SELECT * FROM table WHERE name=?");
$stm->execute(array($_POST['name']));
$user = $stm->fetch();
if ($user) { // <---HERE YOU GO
The in_array() does not work with multi-dimensional arrays. You better flatten your array and then do a search for the keyword.
$it = new RecursiveIteratorIterator(new RecursiveArrayIterator($arr)); //<-- Pass your array here
$new_arr = array();
foreach($it as $v) {
$new_arr[]=$v;
}
if(in_array('test',$new_arr))
{
echo "Exists !";
}
Working Demo
You are searching a 2-D array for a value under the key of "name".
Using array_map() or simple foreach loop should work -
$username = "admin";
$key = "name";
if(!in_array($username,array_map(function($v)use($key){return $v[$key];},$allUsers))){
echo "No found";
}else{
echo "Found";
}
If you are using:
While ($ row=mysql_fetch_assoc ($ result) {
$ data [] = $ row
}
Remove the [] to not create a multidimensional array.
I am working on generating XML file using simpleXml...I have the following code.
require_once('inc.php');
$query = $glb_connection->prepare('select * from table order by ID');
$query->execute();
$tree = $query->fetchAll();
$doc = $xml->init();
foreach($tree as $tr){
$xml_events = $doc->addChild('entr');
$xml_events->addAttribute('ID', $tr['ID']);
$xml_events->addAttribute('cmp', $tr['cmp']);
// add another child
$xml_supervisor = $xml_events->addChild('personDetail');
// instatiate class
$pro = new profile();
// passing getDetail method
$person = $pro->getDetail($tr['ID']);
// it prints all the detail of the ID as expected (using it to check if return true)
print_arr($person);
$xml_supervisor->addAttribute('firstname', $person->lastname);
$xml_supervisor->addAttribute('familyname', $person['lastname']);
}
$file = 'example.xml';
$xml->saveXML($doc,$file);
from the above code, the problem is here...I try to call the field-name from the result object person, but both way I have tried doesn't work...
$xml_supervisor->addAttribute('firstname', $person->lastname);
$xml_supervisor->addAttribute('familyname', $person['lastname']);
how can I call any key or value from generated result of person Object???
some one has help...
This is how the array generated when I call
print_arr($person);
Array
(
[0] => Array
(
[ID] => 10
[lastname] => Sara
)
)
Ohhh, Sorry to bother you every-one, I have found the problem...I don't know what is wrong with me today, any way...
Some one might need it the exact answer some-day, so here it is....
the array is Associative-array in which if we need to call ID it should be like this..
array[0][ID]...means
this should be called like this..
$xml_supervisor->addAttribute('familyname', $person[0]['lastname']);
That is it.
I have this query:
SELECT carID FROM reservations WHERE startDate < '".$sqlretdate."' AND endDate > '".$sqlcoldate."' OR startDate = '".$sqlcoldate."' OR endDate = '".$sqlretdate."'"
Using a loop:
while($presentid = mysql_fetch_array($checkreservations)) {
This returns an array of data, so for example:
echo "<---space-->";
print_r($presentid['carID']);
Would display:
<---space-->11<---space-->10<---space-->2<---space-->8<---space-->9<---space-->7
This is a list of ids, I need to do something with each of them.
I can explode it:
print_r(explode(" ", $presentid['carID']));
And this would make it print like this:
Array ( [0] => 11 ) Array ( [0] => 10 ) Array ( [0] => 2 ) Array ( [0] => 8 ) Array ( [0] => 9 ) Array ( [0] => 7 )
How do I totally split each id and store it into a variable, so I can use them to do something else?
In this case each ID is unique to a car, and has a model name associated to it, so I want to use the id to find out which model name is related to it, count the number of that model name in the database, and then check to see how many of the returned ids related to that model, and therefore how many there is left. I hope that makes sense.
In your while loop, $presentid represents each row in the result set. $presentid['carID'] is not an array! It's one carID value. You do not need to use explode here at all.
while($presentid = mysql_fetch_array($checkreservations)) {
// This *is* each car ID! Do with it what you want.
$carID = $presentid['carID'];
}
$ids = array();
$count = 0;
while($presentid = mysql_fetch_array($checkreservations)) {
$ids['car_' . $count++] = $presentid['carID'];
}
extract($ids);
This will give you independent variables:
$car_0 = 11;
$car_1 = 12;
$car_2 = 2;
..etc
You can't store it into a basic variable without overwriting it, unless you want to reserve very many variables, It's best to go through the loop, store the values into an array, then you can walk trough the array once the while loop is over, unless you can just do something with them right away.
"How do I totally split each id and store it into a variable"
while($presentid = mysql_fetch_array($checkreservations))
{
$carId = $presentid['carID'];
$array[] = array('id' => $carId );
}
So you can parse through the array once It's over.
now a days I am playing with PHPUnit. I have gone through its documentation but I am unable to understand it well. Let me explain my case.
I have a function in a class which takes three parameters 1 array, 2 some string, 3 a class object.
This function returns the array by putting second parameter as an index of the array and result as object of that index. My function is as below
public function construct($testArray, $test,$analysisResult) {
$postedTest = explode('_', $test);
$testName = end($postedTest);
$postedTest = implode("_", array_slice($postedTest, 0, -1));
if (in_array($postedTest, array_keys($testArray))) {
$testArray[$postedTest][$testName] = $analysisResult;
} else {
$testArray[$postedTest] = array($testName => $analysisResult);
}
return $testArray;
}
If I call this function like
$constructObj = new Application_Model_ConstructTree();
$test=$this->getMockForAbstractClass('Abstract_Result');
$test->level = "Error";
$test->infoText = "Not Immplemented";
$testArray = Array('databaseschema' => Array('Database' => $test));
$result = $constructObj->construct($testArray,"Database",$test);
The function returns the array like
Array
(
[databaseschema] => Array
(
[Database] => AnalysisResult Object
(
[isRepairable] => 1
[level] => Error
[infoText] => Not Implemented
)
)
)
Now I want to write a PHPUnit Test to check that the attributes of object like isRepairable, level and infoText exists and not empty. I have gone an idea that assertNotEmpty and assertAttributeEmpty can do some thing But I am unable to understand how to do it.
My test looks like
public function testcontruct() {
$constructObj = new Application_Model_ConstructTree();
$test=$this->getMockForAbstractClass('Abstract_Result');
$test->level = "Error";
$test->infoText = "Not Immplemented";
$testArray = Array('databaseschema' => Array('Database' => $test));
$result = $constructObj->construct($testArray,"Database",$test);
$this->assertNotCount(0, $result);
$this->assertNotContains('databaseschema', $result);
}
Can anyone please guide :-)
The last line should be assertContains instead assertNotContains. The next steps in your test would be:
$this->assertContains('Database', $result['databaseschema']);
$this->assertAttributeNotEmpty('isRepairable', $result['databaseschema']['Database']);
$this->assertAttributeNotEmpty('level', $result['databaseschema']['Database']);
$this->assertAttributeNotEmpty('infoText', $result['databaseschema']['Database']);
assertAttributeNotEmpty takes the attribute name and the object as parameters, just as assertContains takes the array key and the array.
I'd use assertArrayHasKey ie:
$this->assertArrayHasKey($key, $array);
Because you need to test a complex structure, what I'd do is going to each one of the expected elements and assert that they are there, and they are not empty with assertNotEmpty()
I found this a good example, similar to your problem:
http://opensourceame.com/asserting-that-an-array-contains-another-array-in-phpunit/