Get specific value from PHP array using foreach key value - php

I have the following array:
array(15) {
[0]=> object(stdClass)#317 (2) { ["id"]=> string(1) "2" ["value"]=> string(1) "1" }
[1]=> object(stdClass)#316 (2) { ["id"]=> string(1) "3" ["value"]=> string(531) "awfaww" }
[2]=> object(stdClass)#315 (2) { ["id"]=> string(1) "4" ["value"]=> string(1) "1" }
[3]=> object(stdClass)#318 (2) { ["id"]=> string(1) "5" ["value"]=> string(1) "1" }
[4]=> object(stdClass)#319 (2) { ["id"]=> string(1) "6" ["value"]=> string(1) "1" }
[5]=> object(stdClass)#320 (2) { ["id"]=> string(1) "7" ["value"]=> string(1) "1" }
[6]=> object(stdClass)#321 (2) { ["id"]=> string(1) "8" ["value"]=> string(1) "1" }
[7]=> object(stdClass)#322 (2) { ["id"]=> string(2) "30" ["value"]=> string(8) "12:30:02" }
[8]=> object(stdClass)#323 (2) { ["id"]=> string(2) "31" ["value"]=> string(8) "18:12:00" }
[9]=> object(stdClass)#324 (2) { ["id"]=> string(2) "11" ["value"]=> string(10) "2014-06-17" }
[10]=> object(stdClass)#325 (2) { ["id"]=> string(2) "12" ["value"]=> string(10) "2014-06-26" }
[11]=> object(stdClass)#326 (2) { ["id"]=> string(2) "14" ["value"]=> string(1) "2" }
[12]=> object(stdClass)#327 (2) { ["id"]=> string(2) "15" ["value"]=> string(1) "2" }
[13]=> object(stdClass)#328 (2) { ["id"]=> string(2) "16" ["value"]=> string(1) "4" }
[14]=> object(stdClass)#329 (2) { ["id"]=> string(2) "17" ["value"]=> string(1) "5" }
}
I would like to get a specific value from this array using the ID. For example, if the ID: 11 is found in the array I want to retrieve its value. How can I do this?

Try something like this:
<?php
function findById($array, $id) {
foreach ($array as $value) {
if ($value->id == $id) {
return $value->value;
}
}
return null;
}
$result = findById($yourArray, 11);
?>

if the array is static for each run - i'd suggest changing the array into "key"=>"value" array, using this:
$new_arr = array();
foreach($original_array as $object) {
$new_arr[$object->id] = $object->value;
}
and then you can just use $new_arr[id], instead of searching the whole original array each time.

You can use array_filter:
array_filter($arr, function($i) { return $i->id == '11'; });
See Documentation

Related

Creating multidimensional array PHP

I'm attempting to create a multidimensional array which should have the ID and quantity from the $_POST array. At the moment it seems to put every quantity into each an element with each ID.However I want it to take the first elements from each array and then add them together to a new array and so on.
Whereas it should be
ID 1 - Quantity 100
ID 2 - Quantity 50
etc
But at the moment I get this
array(16) {
[0]=>
array(2) {
["id"]=>
string(1) "1"
["quantity"]=>
string(2) "50"
}
[1]=>
array(2) {
["id"]=>
string(1) "1"
["quantity"]=>
string(3) "100"
}
[2]=>
array(2) {
["id"]=>
string(1) "1"
["quantity"]=>
string(3) "100"
}
[3]=>
array(2) {
["id"]=>
string(1) "1"
["quantity"]=>
string(3) "100"
}
[4]=>
array(2) {
["id"]=>
string(2) "12"
["quantity"]=>
string(2) "50"
}
[5]=>
array(2) {
["id"]=>
string(2) "12"
["quantity"]=>
string(3) "100"
}
[6]=>
array(2) {
["id"]=>
string(2) "12"
["quantity"]=>
string(3) "100"
}
[7]=>
array(2) {
["id"]=>
string(2) "12"
["quantity"]=>
string(3) "100"
}
[8]=>
array(2) {
["id"]=>
string(1) "2"
["quantity"]=>
string(2) "50"
}
[9]=>
array(2) {
["id"]=>
string(1) "2"
["quantity"]=>
string(3) "100"
}
[10]=>
array(2) {
["id"]=>
string(1) "2"
["quantity"]=>
string(3) "100"
}
[11]=>
array(2) {
["id"]=>
string(1) "2"
["quantity"]=>
string(3) "100"
}
[12]=>
array(2) {
["id"]=>
string(1) "6"
["quantity"]=>
string(2) "50"
}
[13]=>
array(2) {
["id"]=>
string(1) "6"
["quantity"]=>
string(3) "100"
}
[14]=>
array(2) {
["id"]=>
string(1) "6"
["quantity"]=>
string(3) "100"
}
[15]=>
array(2) {
["id"]=>
string(1) "6"
["quantity"]=>
string(3) "100"
}
}
Here is my PHP code.
foreach($_POST['sweetids'] as $id) {
foreach($_POST['quantites'] as $quantity) {
$stock_array[] = array(
"id"=> $id,
"quantity" => $quantity
);
}
}
I think this is what you're trying to achieve:
foreach($_POST['sweetids'] as $key=>$id) {
$stock_array[] = array(
"id"=> $id,
"quantity" => $_POST['quantities'][$key]
);
}
You're iterating $_POST['quantities'] for every $_POST['sweetids'] which is probably not what you intend. When you iterate both, your result will be every combination of sweetids and quantities, not each pair of them.
I'm guessing you meant something more like:
// Assuming you already verified that $_POST['quantities'] and $_POST['sweetids'] exist
// and that both of them have the same number of elements
for ( $i = 0, $len = count($_POST['sweetids']); $i < $len; $i++ ) {
$stock_array[] = array(
'id' => $_POST['sweetids'][$i],
'quantity' => $_POST['quantities'][$i]
);
}

Codeigniter 2.x, ActiveRecord, var_dump(), what is the expected result?

I am trying to debug some problems I am having with viewing data from a database. I am using codeigniter 2.x and active records. Here is my code:
$data = $this->db->select('country_id', 'country')->from('mhcountry')->get()->result();
var_dump($data);
die;
Var_dump returns the following:
array(20) { [0]=> object(stdClass)#21 (1) { ["country_id"]=> string(1) "1" } [1]=> object(stdClass)#22 (1) { ["country_id"]=> string(1) "2" } [2]=> object(stdClass)#23 (1) { ["country_id"]=> string(1) "3" } [3]=> object(stdClass)#24 (1) { ["country_id"]=> string(1) "4" } [4]=> object(stdClass)#25 (1) { ["country_id"]=> string(1) "5" } [5]=> object(stdClass)#26 (1) { ["country_id"]=> string(1) "6" } [6]=> object(stdClass)#27 (1) { ["country_id"]=> string(1) "7" } [7]=> object(stdClass)#28 (1) { ["country_id"]=> string(1) "8" } [8]=> object(stdClass)#29 (1) { ["country_id"]=> string(1) "9" } [9]=> object(stdClass)#30 (1) { ["country_id"]=> string(2) "10" } [10]=> object(stdClass)#31 (1) { ["country_id"]=> string(2) "11" } [11]=> object(stdClass)#32 (1) { ["country_id"]=> string(2) "12" } [12]=> object(stdClass)#33 (1) { ["country_id"]=> string(2) "13" } [13]=> object(stdClass)#34 (1) { ["country_id"]=> string(2) "14" } [14]=> object(stdClass)#35 (1) { ["country_id"]=> string(2) "15" } [15]=> object(stdClass)#36 (1) { ["country_id"]=> string(2) "16" } [16]=> object(stdClass)#37 (1) { ["country_id"]=> string(2) "17" } [17]=> object(stdClass)#38 (1) { ["country_id"]=> string(2) "18" } [18]=> object(stdClass)#39 (1) { ["country_id"]=> string(2) "19" } [19]=> object(stdClass)#40 (1) { ["country_id"]=> string(2) "20" } }
I have 20 countries entered from 1 to 20 BUT I do not see my country names in the var_dump. It is just dumping the first field. Is this normal or expected?
I tried the same thing on another table and it also just returns the first field.
You should pay attention to the documentation here, meanwhile you can try this :
$this->db->select(array('country_id', 'country'))
// OR
$this->db->select('country_id, country')
$data = $this->db->select('country_id', 'country')->from('mhcountry')->get()->result();
This is wrong. it will get only country_id.
Use this
$data = $this->db->select('country_id , country')->from('mhcountry')->get()->result();

Secondary Drop Down with Preloaded options

I have Sub-Categories that are related to a Main Category. My sub cat table has the main category id as a foreign key. I'd like to preload all subcategories using javascript and avoid an extra php file or db query if possible.
Both dropdowns are listing all the records but...
I'd like my second dropdown list of sub-categories to change dynamically onChange (select) of the first dropdown based on the first dropdown's value which is the main cat id.
Example,
$data = $this->Category->MainCategory->findall();
$this->set('data',$data);
$data2 = $this->Category->SubCategory->findall();
$this->set('data2',$data2);
My arrays look like this:
var_dump ($data) =
array(5) {
[0]=> array(1) { ["MainCategory"]=> array(3) { ["id"]=> string(1) "1" ["name"]=> string(10) "Accounting" ["doctype"]=> string(1) "2" } }
[1]=> array(1) { ["MainCategory"]=> array(3) { ["id"]=> string(1) "2" ["name"]=> string(15) "Human Resources" ["doctype"]=> string(1) "2" } }
[2]=> array(1) { ["MainCategory"]=> array(3) { ["id"]=> string(1) "4" ["name"]=> string(5) "Clubs" ["doctype"]=> string(1) "2" } }
[3]=> array(1) { ["MainCategory"]=> array(3) { ["id"]=> string(1) "8" ["name"]=> string(16) "Service" ["doctype"]=> string(1) "2" } }
[4]=> array(1) { ["MainCategory"]=> array(3) { ["id"]=> string(2) "10" ["name"]=> string(9) "Safety" ["doctype"]=> string(1) "2" } } }
var_dump($data2) =
array(20) {
[0]=> array(1) { ["SubCategory"]=> array(3) { ["id"]=> string(1) "1" ["name"]=> string(17) "Application Forms" ["main_category_id"]=> string(1) "2" } }
[1]=> array(1) { ["SubCategory"]=> array(3) { ["id"]=> string(1) "2" ["name"]=> string(19) "Benefit Claim Forms" ["main_category_id"]=> string(1) "2" } }
[2]=> array(1) { ["SubCategory"]=> array(3) { ["id"]=> string(1) "3" ["name"]=> string(22) "Evaluations" ["main_category_id"]=> string(1) "2" } }
[3]=> array(1) { ["SubCategory"]=> array(3) { ["id"]=> string(1) "4" ["name"]=> string(11) "Leave Forms" ["main_category_id"]=> string(1) "2" } }
[4]=> array(1) { ["SubCategory"]=> array(3) { ["id"]=> string(1) "5" ["name"]=> string(13) "Payroll" ["main_category_id"]=> string(1) "2" } }
[5]=> array(1) { ["SubCategory"]=> array(3) { ["id"]=> string(1) "6" ["name"]=> string(17) "Recruitment" ["main_category_id"]=> string(1) "2" } }
[6]=> array(1) { ["SubCategory"]=> array(3) { ["id"]=> string(1) "7" ["name"]=> string(24) "Training" ["main_category_id"]=> string(1) "2" } }
[7]=> array(1) { ["SubCategory"]=> array(3) { ["id"]=> string(1) "8" ["name"]=> string(10) "Accounting" ["main_category_id"]=> string(1) "1" } }
[8]=> array(1) { ["SubCategory"]=> array(3) { ["id"]=> string(1) "9" ["name"]=> string(13) "Staff" ["main_category_id"]=> string(1) "2" } }
[9]=> array(1) { ["SubCategory"]=> array(3) { ["id"]=> string(2) "10" ["name"]=> string(14) "Codes" ["main_category_id"]=> string(2) "3" } }
[10]=> array(1) { ["SubCategory"]=> array(3) { ["id"]=> string(2) "11" ["name"]=> string(28) "Reports" ["main_category_id"]=> string(2) "3" }
[11]=> array(1) { ["SubCategory"]=> array(3) { ["id"]=> string(2) "12" ["name"]=> string(14) "Plan" ["main_category_id"]=> string(2) "4" } }
[12]=> array(1) { ["SubCategory"]=> array(3) { ["id"]=> string(2) "13" ["name"]=> string(21) "Charts" ["main_category_id"]=> string(2) "4" } }
[13]=> array(1) { ["SubCategory"]=> array(3) { ["id"]=> string(2) "14" ["name"]=> string(11) "Travel" ["main_category_id"]=> string(1) "4" } }
[14]=> array(1) { ["SubCategory"]=> array(3) { ["id"]=> string(2) "15" ["name"]=> string(15) "Financials" ["main_category_id"]=> string(1) "4" } }
[15]=> array(1) { ["SubCategory"]=> array(3) { ["id"]=> string(2) "16" ["name"]=> string(19) "Event Planning" ["main_category_id"]=> string(1) "4" } }
[16]=> array(1) { ["SubCategory"]=> array(3) { ["id"]=> string(2) "17" ["name"]=> string(14) "Resources" ["main_category_id"]=> string(1) "4" } }
[17]=> array(1) { ["SubCategory"]=> array(3) { ["id"]=> string(2) "18" ["name"]=> string(11) "Basics" ["main_category_id"]=> string(1) "4" } }
[18]=> array(1) { ["SubCategory"]=> array(3) { ["id"]=> string(2) "19" ["name"]=> string(9) "News" ["main_category_id"]=> string(1) "4" } }
[19]=> array(1) { ["SubCategory"]=> array(3) { ["id"]=> string(2) "20" ["name"]=> string(12) “Funding" ["main_category_id"]=> string(1) "4" } } }
--html form ….
<td>Category: </td>
<td><select id="main_cat">
<option value=""> </option>
<?php foreach($data as $row){
echo "<option value=".$row['MainCategory']['id'].">" .$row['MainCategory']['name']. "</option>";
} ?>
</select></td>
<td>Sub Category: </td>
<td><select id="sub_cat">
<option value=""> </option>
<?php foreach($data2 as $row){
echo "<option value=".$row[‘SubCategory']['id'].">" .$row['SubCategory']['name']. "</option>";
} ?>
</select></td>
…..
Create a two dimensional javascript array loaded with the sub-categories by category id, then reload the second drop down when the first changes. Highly simplified jsfiddle example.
For the php, you'll only need to worry about generating the subCats array. Something along the lines of:
<script type="text/javascript>
var subCats = [
<?php foreach($data2 as $row){
echo "[";
foreach($row as $subcat) {
echo "\"" . $subcat . "\",";
}
echo "]";
} ?>
</script>
just.another.programmer got me on the right track and with some other examples from Jonathan Kuhn, this is the result http://jsfiddle.net/wprLD/9/
<script type="text/javascript">
var subCats =
<?php
$js = array();
foreach($data2 as $sub){
//get the parent id (main_category_id)
$parent = $sub['SubCategory']['main_category_id'];
//if the parent doesn't exist, add it
if(!isset($js[$parent])){
//add array with name and id
$js[$parent] = array(array('id'=>$sub['SubCategory']['id'],'name'=>$sub['SubCategory']['name']));
//parent does exist
} else {
//append this entry name and id
$js[$parent][] = array('id'=>$sub['SubCategory']['id'],'name'=>$sub['SubCategory']['name']);
}
}
$js = array_values($js);
echo json_encode($js);
?>
;
function makeSubCatHtml(catId) {
var subCatHtml = "",
i;
//check if the subcats object has this cat Id.
if(subCats.hasOwnProperty(catId)){
for (i in subCats[catId]) {
subCatHtml += "<option value='"+subCats[catId][i].id+"'>" + subCats[catId][i].name + "</option>";
}
}
return subCatHtml;
}
$(document).ready(function () {
$("#MainCategory").bind("change", function () {
$("#SubCategory").html(
makeSubCatHtml(this.selectedIndex));
});
});
</script>

Use PHP if() to match item in array

I am working on an admin panel in which the code will display different if the PDO query returns all the admins from the admin table and the userid matches 1 of the admin id results. Only there can be an unlimited amount of admins and I don't want to be editing the code for each of them.
Would it be possible to do this (pseudo code):
if($userid isfoundin $result['admin_user_id']{
-- admin code here
}
I haven't yet written the admin table as I want more info on it first but if I cycle through the user table and look for id $query->fetchAll() then I get this:
array(30) { [0]=> array(2) { ["id"]=> string(1) "7" [0]=> string(1) "7" } [1]=> array(2) { ["id"]=> string(1) "6" [0]=> string(1) "6" } [2]=> array(2) { ["id"]=> string(1) "8" [0]=> string(1) "8" } [3]=> array(2) { ["id"]=> string(2) "31" [0]=> string(2) "31" } [4]=> array(2) { ["id"]=> string(2) "26" [0]=> string(2) "26" } [5]=> array(2) { ["id"]=> string(1) "4" [0]=> string(1) "4" } [6]=> array(2) { ["id"]=> string(2) "35" [0]=> string(2) "35" } [7]=> array(2) { ["id"]=> string(2) "21" [0]=> string(2) "21" } [8]=> array(2) { ["id"]=> string(2) "38" [0]=> string(2) "38" } [9]=> array(2) { ["id"]=> string(2) "24" [0]=> string(2) "24" } [10]=> array(2) { ["id"]=> string(2) "34" [0]=> string(2) "34" } [11]=> array(2) { ["id"]=> string(2) "20" [0]=> string(2) "20" } [12]=> array(2) { ["id"]=> string(2) "19" [0]=> string(2) "19" } [13]=> array(2) { ["id"]=> string(2) "23" [0]=> string(2) "23" } [14]=> array(2) { ["id"]=> string(2) "33" [0]=> string(2) "33" } [15]=> array(2) { ["id"]=> string(2) "28" [0]=> string(2) "28" } [16]=> array(2) { ["id"]=> string(1) "3" [0]=> string(1) "3" } [17]=> array(2) { ["id"]=> string(2) "15" [0]=> string(2) "15" } [18]=> array(2) { ["id"]=> string(1) "9" [0]=> string(1) "9" } [19]=> array(2) { ["id"]=> string(2) "25" [0]=> string(2) "25" } [20]=> array(2) { ["id"]=> string(1) "1" [0]=> string(1) "1" } [21]=> array(2) { ["id"]=> string(2) "32" [0]=> string(2) "32" } [22]=> array(2) { ["id"]=> string(1) "5" [0]=> string(1) "5" } [23]=> array(2) { ["id"]=> string(2) "18" [0]=> string(2) "18" } [24]=> array(2) { ["id"]=> string(2) "29" [0]=> string(2) "29" } [25]=> array(2) { ["id"]=> string(2) "27" [0]=> string(2) "27" } [26]=> array(2) { ["id"]=> string(2) "30" [0]=> string(2) "30" } [27]=> array(2) { ["id"]=> string(2) "22" [0]=> string(2) "22" } [28]=> array(2) { ["id"]=> string(2) "10" [0]=> string(2) "10" } [29]=> array(2) { ["id"]=> string(2) "36" [0]=> string(2) "36" } }
this si what I am trying to use right now
require_once $_SERVER['DOCUMENT_ROOT']."/resources/settings.php";
$query = $pdo->prepare("SELECT id FROM users");
$query->execute();
var_dump($query->fetchAll());
if (in_array($user['id'], $query->fetchAll())){
echo $user['id'];
}
Yes, you can use in_array() for this.
I assume that you have a set of users for admin. Say, it is:
$adminUsers = array("admin", "administrator");
# Or by your code
$adminUsers = $result['admin_user_id'];
Now the code part is like:
if (in_array($userid, $adminUsers))
// Admin code here
I think you're looking for in_array() to see if a given item is in an array.
You should use in_array() if all you need to know is that the user ID exists in your array.
But if you actually need a reference to the item, take a look at array_search() http://au1.php.net/manual/en/function.array-search.php
Instead of going through all the users in your admins table and then having another loop in order to find if a specific user exists , why not doing this check in the query itself?
For instance:
$stmt = $mysqli->prepare("SELECT name,email FROM admins WHERE id=?");
$stmt->bind_param("d", $user_id);
$stmt->execute();
$stmt->bind_result($name, $email);
if ($stmt->fetch()) {
//The user with user_id exists in the admins table , show him the admin panel.
//You can use $name and $email.
}
$stmt->close();

PHP Group By Day

Given this array:
array(1) {
[0]=>
array(2) {
["Project"]=>
array(5) {
["id"]=>
string(1) "2"
["user_id"]=>
string(2) "21"
["customer_id"]=>
string(1) "4"
["name"]=>
string(15) "WordPress Theme"
["created"]=>
string(19) "2011-09-26 21:30:38"
}
["Track"]=>
array(1) {
[0]=>
array(8) {
["id"]=>
string(1) "7"
["user_id"]=>
string(2) "21"
["project"]=>
string(1) "2"
["customer"]=>
string(1) "4"
["title"]=>
string(7) "Backend"
["notes"]=>
string(0) ""
["created"]=>
string(19) "2011-09-28 22:21:22"
["Lapse"]=>
array(2) {
[0]=>
array(5) {
["id"]=>
string(1) "4"
["track_id"]=>
string(1) "7"
["start"]=>
string(19) "2011-09-28 22:22:21"
["stop"]=>
string(19) "2011-09-28 22:22:30"
["created"]=>
string(19) "2011-09-28 22:22:21"
}
[1]=>
array(5) {
["id"]=>
string(1) "3"
["track_id"]=>
string(1) "7"
["start"]=>
string(19) "2011-09-28 22:22:07"
["stop"]=>
string(19) "2011-09-28 22:22:12"
["created"]=>
string(19) "2011-09-28 22:22:07"
}
}
}
}
}
}
How would i group by Day in the Lapse Array with PHP? This may have been easier to do directly with MySQL but i'm using CakePHP's recursive function and i cant figure out how to use Group By with that!
$list = array();
function extractByDates($arr) {
foreach ($arr as $key => $v)
if (is_array($v))
function extractByDates($v);
else if ($key == 'created')
$list[$v] = $v;
}
extractByDates($yourGivenArray);
I not tested!

Categories