How to fetch arrays with string in php - php

how can i fetch data in an arrays with gives null value if null
here is my data I var_dump($showStatus); I want to print out . $showStatus[0]['title']
string(0) ""
array(2) {
[0]=>
array(7) {
["id"]=>
string(1) "1"
["container_id"]=>
string(1) "3"
["title"]=>
string(51) "waitting"
}
[1]=>
array(7) {
["id"]=>
string(1) "2"
["container_id"]=>
string(1) "3"
["title"]=>
string(72) "getting"
}
}
array(1) {
[0]=>
array(7) {
["id"]=>
string(1) "4"
["container_id"]=>
string(1) "7"
["title"]=>
string(51) "getting"
}
}
The reason that I've string because in my models I want to print "" or NULL when it don't have data here is my models
public function showStatus($id){
$sql = 'SELECT * FROM status WHERE container_id = '.$id;
if($this->query_rows( $sql )) {
return $this->query_rows($sql);
} else {
return "";
}
}
I try to use
foreach ($getListData as $k) {
}
but it said Warning: Invalid argument supplied for foreach()

Try this:
if(!empty($getListData) )
{
foreach ($getListData as $k) {
print_r($k);
}
}
else {
echo "NULL";
}

Related

Array data manipulations PHP

I get from my DB data in format like this:
array(12) {
[0]=>
array(4) {
["id"]=>
string(1) "1"
["count"]=>
string(5) "78984"
["month"]=>
string(1) "6"
["hours"]=>
string(10) "10580.0833"
}
[1]=>
array(4) {
["id"]=>
string(1) "2"
["count"]=>
string(5) "64174"
["month"]=>
string(1) "6"
["hours"]=>
string(9) "6866.8333"
}
[2]=>
array(4) {
["id"]=>
string(1) "3"
["count"]=>
string(5) "31032"
["month"]=>
string(1) "6"
["hours"]=>
string(9) "3700.9167"
}
[3]=>
array(4) {
["id"]=>
string(1) "1"
["count"]=>
string(5) "91114"
["month"]=>
string(1) "7"
["hours"]=>
string(10) "11859.6000"
}
...
Each of array inside has a key: "id". It mostly look values from 1 to 3. I would like to create a new array based on this "ids" that would look like this:
array("number of unique ids") {
[0]=> "for id = 0"
array(12) {
int() count/hours
int() count/hours
int() count/hours
...
}
[1]=> "for id = 1 and so on..."
array(12){
....
}
I`ve been trying to do it like this:
$data1 = [];
$data2 = [];
$data3 = [];
foreach($data as $key => $record){
if($record['id'] == 1){
array_push($data1, $record['count']/$record['hours']);
}else if($data['id_zmiana'] == 2){
array_push($data2, $record['count']/$record['hours']);
}else{
array_push($data3, $record['count']/$record['hours']);
}
}
$raport = array_merge($data1, $data2, $data3);
And that would work, but it doesn`t look good in my opinion, beacuse what if the id change to some big number.
Yeah, having separate arrays for each ID is not a good idea. How about:
$raport = [];
foreach ($data as $record) {
$raport[$record['id']][] = $record['count'] / $record['hours']);
}
Simple, and straight to the point.
Haven't tested it. Next time try to use var_export() to export the data you put in your question. That way we can actually use it, without having to rewrite it completely.

Search with PHP inside MongoDB

Im trying many days now to select data from this db
[1]: https://i.stack.imgur.com/QA34L.jpg
I want to print for example all comments
echo $comment['username']." | "; \ Alex | Alex
My php code so far:
[![$m= new MongoDB\Client ("mongodb://127.0.0.1/");
$db = $m->stores;
$collection = $db->storeinfo;][1]][1]
$storez = $collection->find(array("Products.pTHUMBNAIL" => $pThumb));
$o=1;
$afm=array();
foreach ($storez as $stor) {
$afm[$o] = $stor['AFM'];
$record = $collection->findOne(array(
"AFM" => $afm[$o],"Products.pTHUMBNAIL" => $pThumb));
foreach ($record['Products'] as $pro){
if($pThumb == $pro['pTHUMBNAIL']){
echo $temp = $pro['pID']." ";
foreach($pro as $pro1['pCOMMENTS']) {
foreach($pro1 as $com['Comment']) {
var_dump($com['Comment']);
/*
foreach($com as $comment) {
echo $comment['username'];
}
*/
}
}
}
}
$o += 1;
}
It seems that i just cannot find the correct foreach to loop through my Comment array
var_dump output:
099360111/1 object(MongoDB\BSON\ObjectId)#55 (1) { ["oid"]=> string(24) "6003403a695900000c002649" } string(11) "099360111/1" string(9) "Old Skool" string(2) "75" string(4) "Vans" string(25) "Leather and textile upper" string(2) "44" string(18) "Men/Shoes/Trainers" string(52) "http://127.0.0.1/pricedoc/assets/img/products/p1.jpg" string(1) "7" object(MongoDB\Model\BSONArray)#65 (1) { ["storage":"ArrayObject":private]=> array(1) { [0]=> object(MongoDB\Model\BSONDocument)#10 (1) { ["storage":"ArrayObject":private]=> array(1) { ["Comment"]=> object(MongoDB\Model\BSONDocument)#73 (1) { ["storage":"ArrayObject":private]=> array(4) { ["username"]=> string(4) "Alex" ["date"]=> object(MongoDB\BSON\UTCDateTime)#45 (1) { ["milliseconds"]=> string(13) "1611028053000" } ["text"]=> string(21) "1st comment from user" ["rating"]=> string(1) "4" } } } } } } 099360666/1 object(MongoDB\BSON\ObjectId)#44 (1) { ["oid"]=> string(24) "6006563a3f1c0000c80034a8" } string(11) "099360666/1" string(12) "old school 2" string(2) "50" string(4) "Vans" string(11) "black/white" string(8) "42,43,43" string(18) "Men/Shoes/Trainers" string(52) "http://127.0.0.1/pricedoc/assets/img/products/p1.jpg" string(1) "6" object(MongoDB\Model\BSONArray)#79 (1) { ["storage":"ArrayObject":private]=> array(2) { [0]=> object(MongoDB\Model\BSONDocument)#7 (1) { ["storage":"ArrayObject":private]=> array(1) { ["Comment"]=> object(MongoDB\Model\BSONDocument)#39 (1) { ["storage":"ArrayObject":private]=> array(4) { ["username"]=> string(4) "Alex" ["date"]=> object(MongoDB\BSON\UTCDateTime)#68 (1) { ["milliseconds"]=> string(13) "1611028089000" } ["text"]=> string(21) "1st comment from user" ["rating"]=> string(1) "4" } } } } [1]=> object(MongoDB\Model\BSONDocument)#78 (1) { ["storage":"ArrayObject":private]=> array(1) { ["Comment"]=> object(MongoDB\Model\BSONDocument)#77 (1) { ["storage":"ArrayObject":private]=> array(4) { ["username"]=> string(4) "Alex" ["date"]=> object(MongoDB\BSON\UTCDateTime)#76 (1) { ["milliseconds"]=> string(13) "1611030745000" } ["text"]=> string(8) "good!!!!" ["rating"]=> string(1) "5" } } } } } }
What about this?
After echo $temp = $pro['pID']." ";
foreach($pro['pCOMMENTS'] as $comments) {
foreach ($comments['Comment'] as $comment) {
echo $comment['text'];
}
}
You used foreach() bad: the index should be added to the first parameter, not in the 'as' part.
Also it helps if you use more clear variable names. That doesn't take too much, but makes it more readable and easy to debug.
After echo $temp = $pro['pID']." ";
foreach($pro['pCOMMENTS'] as $comments) {
foreach($comments as $comment) {
echo $comment['text'];
}
}

how to get the index of every array on multidimensional array with unknown depth in php

array(2) { [0]=> array(2) { ["name"]=> string(16) "Daerah Pertanian" ["sub"]=> array(6) { [0]=> array(2) { ["name"]=> string(5) "Sawah" ["value"]=> string(3) "145" } [1]=> array(2) { ["name"]=> string(18) "Sawah Pasang Surut" ["value"]=> string(3) "455" } [2]=> array(2) { ["name"]=> string(6) "Ladang" ["value"]=> string(3) "678" } [3]=> array(2) { ["name"]=> string(10) "Perkebunan" ["value"]=> string(3) "688" } [4]=> array(2) { ["name"]=> string(19) "Perkebunan Campuran" ["value"]=> string(3) "966" } [5]=> array(2) { ["name"]=> string(16) "Tanaman Campuran" ["value"]=> string(3) "565" } } } [1]=> array(2) { ["name"]=> string(22) "Daerah Bukan Pertanian" ["sub"]=> array(2) { [0]=> array(2) { ["name"]=> string(18) "Hutan Lahan Kering" ["sub"]=> array(2) { [0]=> array(2) { ["name"]=> string(25) "Hutan Lahan Kering Primer" ["value"]=> string(3) "566" } [1]=> array(2) { ["name"]=> string(27) "Hutan Lahan Kering Sekunder" ["value"]=> string(3) "255" } } } [1]=> array(2) { ["name"]=> string(17) "Hutan Lahan Basah" ["sub"]=> array(2) { [0]=> array(1) { ["name"]=> string(24) "Hutan Lahan Basah Primer" } [1]=> array(1) { ["name"]=> string(26) "Hutan Lahan Basah Sekunder" } } } } } }
I have an array like I mention above, so I want to print out every "name" key including the index (number) of it's array parent,
for example when I print out "Tanaman Campuran" so all index parent is (0)(5) and when I print "Hutan Lahan Basah Sekunder" the index parent is (1)(1)(1)
how can I achieve it?
here is some recursive function that I've tried
$GLOBALS['all'] = '';
function printout($arr){
foreach ($arr as $ia=>$a){
if(is_array($a)){
foreach ($a as $ib=>$b){
if(is_array($b)){
printout($b);
}
else{
if ($ib == 'name') {
$GLOBALS['all'] .= $ia;
echo '<tr>';
echo '<td>' . $b . ' (' . $ia . ')</td>';
echo '</tr>';
$GLOBALS['all'] = '';
}
}
}
}
}
}
*sorry for my bad explanation, I hope you guys can understand it
You could use the following function:
function search(array $array, $name)
{
foreach ($array as $key => $entry) {
if ($entry['name'] === $name) {
return [$key];
}
if (isset($entry['sub']) && $found_keys = search($entry['sub'], $name)) {
return array_merge([$key], $found_keys);
}
}
return null;
}
It returns:
if the value was directly found, an array of one containing the associated index,
if it wasn't but was found in any descendant item, an array merging its index with the indices of said descendant,
null if it wasn't found in that part of the tree.
Note: if a given name is present several times, it will only find the first occurrence.
Demo: https://3v4l.org/1hGr1

$_POST values changing or disappearing inside foreach loop

Prior to this foreach loop $_POST['encounterName'] contains a predefined name. Inside the loop its value changes to ".json" so the first string in file_put_contents reads ".json.json". As well $_POST['basicTrainingSectionSlide'], $_POST['basicTrainingContentHeader'], and
$_POST['basicTrainingContentText'] lose their values. After the foreach loop, all values go back to normal. What is happening here?
$i = 0;
$j = 0;
foreach($_POST['Sections'] as $order){
if(strcmp($order, "Section") == 0){
file_put_contents($_POST['encounterName'].".json", "\t\t[\n", FILE_APPEND);
file_put_contents($_POST['encounterName'].".json", "\t\t\t\"Section\",\n", FILE_APPEND);
file_put_contents($_POST['encounterName'].".json", "\t\t\t\"".$_POST['basicTrainingSectionSlide'][$i]."\"\n", FILE_APPEND);
file_put_contents($_POST['encounterName'].".json", "\t\t],\n", FILE_APPEND);
$i++;
}
else if(strcmp($order, "Text") == 0){
file_put_contents($_POST['encounterName'].".json", "\t\t[\n", FILE_APPEND);
file_put_contents($_POST['encounterName'].".json", "\t\t\t\"Text\",\n", FILE_APPEND);
file_put_contents($_POST['encounterName'].".json", "\t\t\t\"".$_POST['basicTrainingContentHeader'][$j]."\"\n", FILE_APPEND);
file_put_contents($_POST['encounterName'].".json", "\t\t\t\"".$_POST['basicTrainingContentText'][$j]."\"\n", FILE_APPEND);
file_put_contents($_POST['encounterName'].".json", "\t\t],\n", FILE_APPEND);
$j++;
}
}
This is what the $_post array contains:
array(11) { ["encounterName"]=> string(8) "Violence" ["encounterHint"]=> string(0) "" ["basicTrainingSectionSlide"]=> array(2) { [0]=> string(1) "1" [1]=> string(1) "6" } ["basicTrainingContentHeader"]=> array(2) { [0]=> string(1) "2" [1]=> string(1) "4" } ["basicTrainingContentText"]=> array(2) { [0]=> string(1) "3" [1]=> string(1) "5" } ["contextText_1"]=> string(0) "" ["contextText_2"]=> string(0) "" ["contextText_3"]=> string(0) "" ["contextText_4"]=> string(0) "" ["contextText_5"]=> string(0) "" ["submit_form"]=> string(6) "Submit" } array(11) { ["encounterName"]=> string(8) "Violence" ["encounterHint"]=> string(0) "" ["basicTrainingSectionSlide"]=> array(2) { [0]=> string(1) "1" [1]=> string(1) "6" } ["basicTrainingContentHeader"]=> array(2) { [0]=> string(1) "2" [1]=> string(1) "4" } ["basicTrainingContentText"]=> array(2) { [0]=> string(1) "3" [1]=> string(1) "5" } ["submit_form"]=> string(6) "Submit" }
Some added information:
-The form that is filled out sends its post data to a separate php file for processing.
-The $_POST['Sections'] is sent via this function:
function returnValues() {
$.ajax({
type: "POST",
url: "final.php",
data:{ Sections: $sectionOrder },
success: function(data){
console.log(data);
}
})
}
from a .js file onsubmit of the form tag.
Assuming that $_POST['Sections'] contains something like:
array(11) {
["encounterName"]=> string(8) "Violence"
["encounterHint"]=> string(0) ""
["basicTrainingSectionSlide"]=> array(2) {
[0]=> string(1) "1"
[1]=> string(1) "6" }
["basicTrainingContentHeader"]=> array(2) {
[0]=> string(1) "2"
[1]=> string(1) "4" }
["basicTrainingContentText"]=> array(2) {
[0]=> string(1) "3"
[1]=> string(1) "5" }
["contextText_1"]=> string(0) ""
["contextText_2"]=> string(0) ""
["contextText_3"]=> string(0) ""
["contextText_4"]=> string(0) ""
["contextText_5"]=> string(0) ""
["submit_form"]=> string(6) "Submit"
}
array(11) {
["encounterName"]=> string(8) "Violence"
["encounterHint"]=> string(0) ""
["basicTrainingSectionSlide"]=> array(2) {
[0]=> string(1) "1"
[1]=> string(1) "6" }
["basicTrainingContentHeader"]=> array(2) {
[0]=> string(1) "2"
[1]=> string(1) "4" }
["basicTrainingContentText"]=> array(2) {
[0]=> string(1) "3"
[1]=> string(1) "5" }
["submit_form"]=> string(6) "Submit"
}
I would do something like this:
$i = 0;
$j = 0;
foreach($_POST['Sections'] as $order){
$fn = $order['encounterName'] . ".json";
$appText = "";
if(strcmp($order, "Section") == 0){
$appText .= "\t\t[\n";
$appText .= "\t\t\t\"Section\",\n";
$appText .="\t\t\t\"" . $order['basicTrainingSectionSlide'][$i] . "\"\n";
$appText .= "\t\t],\n";
file_put_contents($fn, $appText, FILE_APPEND);
$i++;
} elseif(strcmp($order, "Text") == 0){
$appText .= "\t\t[\n";
$appText .= "\t\t\t\"Text\",\n";
$appText .= "\t\t\t\"" . $order['basicTrainingContentHeader'][$j] . "\"\n";
$appText .= "\t\t\t\"" . $order['basicTrainingContentText'][$j] . "\"\n";
$appText .= "\t\t],\n";
file_put_contents($fn, $appText, FILE_APPEND);
$j++;
}
}
Since you are in a foreach loop and iterating over the array $_POST['Sections'], to call the elements of that array, you need to use $order. That is how you defined the loop. You kept calling $_POST and those indexes shouldn't exist.
If you were using $_POST, the first occurrence of encounterName would be located at $_POST['Sections'][0]['encounterName'] and would contain the string Violence. So, in the loop, $fn = $order['encounterName'].".json"; should be assigned Violence.json as a String.
I am unsure what the if statement is looking for. Since $order is an Array, not a String, strcmp() should return NULL. See notes here. Since both if statements would fail, your file would not be appended in either case. Please comment if you want to clarify that.
I tested the following on http://phpfiddle.org/lite :
<?php
$order = array();
if(strcmp($order, "Section")){
echo "Success";
} else {
echo "Fail";
}
?>
I got the following results:
E_WARNING : type 2 -- strcmp() expects parameter 1 to be string, array given -- at line 5
Fail
This code is untested.

Foreach mysql query from array, then a second query from that first array

Im trying to loop through a query from the result of another query:
public static function getActivityFromUsers()
{
$database = DatabaseFactory::getFactory()->getConnection();
// FETCH USER_ID FOR THE SECOND QUERY
$sql = "SELECT user_id, follower_since_timestamp FROM users_followers where follower_id = :user_id";
$query = $database->prepare($sql);
$query->execute(array(':user_id' => Session::get('user_id')));
if ($query->rowCount() <= 0) {
echo 'Nothing';
return false;
}
$_MYSQL_DATA = $query->fetchAll();
/* Just for my own testing and troubleshoot */
foreach ($_MYSQL_DATA as $row) {
echo $row->user_id . " - " . date('d/m/Y H:i:s', $row->follower_since_timestamp) ."<br/>";
}
echo var_dump($_MYSQL_DATA).'<br><br>';
/* End for my own testing and troubleshoot*/
// USING THE USER_ID´s FROM THE FIRST QUERY TO FETCH DATA FOR OUTPUT
foreach ($_MYSQL_DATA as $row) {
$sql = "SELECT activity, user_id, activity_timestamp FROM user_activity WHERE user_id = :user_id";
$query = $database->prepare($sql);
$query->execute(array(':user_id' => $row->user_id));
$new_data[] = $query->fetchAll();
}
// FOREACH TO OUTPUT DATA FROM SECOND QUERY (SHOULD BE ORDERD BY activity_timestamp)
foreach($new_data as $key => $object){
echo 'User_id: ' . $object->user_id.'<br>';
echo 'What: ' . $object->activity .'<br>';
echo 'When: ' . date('d/m/Y H:i:s', $object->activity_timestamp) .'<br>';
}
echo var_dump($new_data);
}
But this gives me the error: Notice: Trying to get property of non-object in .. User_id: etc..
The var_dump of $new_data[] (from the second query that fetched the data) gives me this: (notice the two arrays in the bottom, why is that? array[2] & array[3])
array(4) {
[0]=> array(7) {
[0]=> object(stdClass)#7 (3) { ["activity"]=> string(15) "Wrote" ["user_id"]=> string(1) "2" ["activity_timestamp"]=> string(10) "1433704851" }
[1]=> object(stdClass)#17 (3) { ["activity"]=> string(15) "Wrote" ["user_id"]=> string(1) "2" ["activity_timestamp"]=> string(10) "1433832032" }
[2]=> object(stdClass)#18 (3) { ["activity"]=> string(15) "Wrote" ["user_id"]=> string(1) "2" ["activity_timestamp"]=> string(10) "1433832033" }
[3]=> object(stdClass)#19 (3) { ["activity"]=> string(15) "Wrote" ["user_id"]=> string(1) "2" ["activity_timestamp"]=> string(10) "1433832035" }
[4]=> object(stdClass)#20 (3) { ["activity"]=> string(7) "Follows" ["user_id"]=> string(1) "2" ["activity_timestamp"]=> string(10) "1433832150" }
[5]=> object(stdClass)#21 (3) { ["activity"]=> string(7) "Wrote" ["user_id"]=> string(1) "2" ["activity_timestamp"]=> NULL }
[6]=> object(stdClass)#22 (3) { ["activity"]=> string(8) "Wrote " ["user_id"]=> string(1) "2" ["activity_timestamp"]=> NULL } }
[1]=> array(1) {
[0]=> object(stdClass)#16 (3) { ["activity"]=> string(19) "Finally!" ["user_id"]=> string(1) "3" ["activity_timestamp"]=> string(10) "1433794873" } }
[2]=> array(0) { }
[3]=> array(0) { } }
How do I properly foreach the result from the second query?
fetchAll returns an Array, not an object.
Replace all your
$object->xxx
by
$object['xxx']
Why not just use a single query..
SELECT
users_followers.user_id,
users_followers.follower_since_timestamp,
a.activity,
a.user_id,
a.activity_timestamp
FROM
users_followers
LEFT JOIN
(SELECT activity, user_id, activity_timestamp FROM user_activity) a
ON a.user_id = users_followers.user_id
where
users_followers.follower_id = :user_id

Categories