I got some array inside array and I want to get all the value of that and store it on variable. This is the structure of my array :
array(5) { ["InventoryID"]=> string(2) "43"
["Price"]=> string(5) "45.36"
["Warehouse"]=> array(2) { ["WID"]=> string(1) "1"
["Quantity"]=> string(1) "12"
}
["Name"]=> string(48) "Bottle"
["SKU"]=> string(8) "M123"
}
array(5) { ["InventoryID"]=> string(2) "51"
["Price"]=> string(5) "21.67"
["Warehouse"]=> array(2) { ["WID"]=> string(1) "1"
["Quantity"]=> string(1) "40"
}
["Name"]=> string(48) "Glass"
["SKU"]=> string(8) "M124"
}
What I want is to get all the value of that array and store it in variable like this :
$inventoryid = 43;
$price = 45.36;
$wid = 1;
$quantity = 12;
$name = 'Bottle';
$sku = 'M123';
What I do till now is I looping that array in foreach but I can't get the second array value. This is what I do till now :
foreach($array as $row)
{
$inventoryid = $row['InventoryID'];
$price = $row['Price'];
$name = $row['Name'];
$sku = $row['SKU'];
foreach($row['Warehouse'] as $row2)
{
$wid = $row2['WID'];
$quantity = $row2['Quantity'];
}
}
How can I do that ? Please anyone give me some code example with foreach to get the value.
I'm struggling to fully understand what benefit you're getting from having these values as variables rather than part of an array. You're still able to access the values quite easily.
Anyway, based on your comment it appears the issue is with the nested array. You don't need a foreach to access those values.
Example:
$wid = $row['Warehouse']['WID'];
$quantity = $row['Warehouse']['Quantity']
Documentation: http://php.net/manual/en/language.types.array.php
you can use recursive for this.
class ProductData
{
public function walkRecursive($a) {
asort($a); //Sort top down
foreach($a as $k => $v){
if(is_array($v)){
$this->walkRecursive($v);
}else{
$this->{$k} = $v;
}
}
return $this;
}
}
$array = array(
"SKU" => "Test1",
"Warehouse" => array("WID" => 1, "Quantity" => 2),
"Name" => "Product1"
);
$d = new ProductData();
$product = $d->walkRecursive($array);
You can now do: $product->SKU. Or $product->Quantity or $Product->Name
Related
I´m trying to get this array
[24]=>
array(2) {
[0]=>
string(1) "21"
[1]=>
string(1) "22"
}
So far I have this:
function Job($conn){
$array = array();
foreach(array_unique($_SESSION['ROLES']) as $value)
{
$sql="SELECT employee,task FROM table WHERE id={$value} AND employee=24";//echo($sql);
$result = $conn->executeSQL($sql);
foreach($result as $value)
{
$array[$value['employee']][] = $value['task'];
}
}
return $array;
}
Which returns the tasks for two values I have store in $_SESSION['ROLES'] but if there are duplicates I need to remove them :
[24]=>
array(4) {
[0]=>
string(1) "21"
[1]=>
string(1) "22"
[2]=>
string(1) "21"
[3]=>
string(1) "22"
}
I can think of two ways to do this.
Use array_unique as indicated by comments.
function Job($conn) {
$array = array();
foreach(array_unique($_SESSION['ROLES']) as $value)
{
$sql="SELECT employee,task FROM table WHERE id={$value} AND employee=24";//echo($sql);
$result = $conn->executeSQL($sql);
$temp = [];
foreach($result as $value)
{
$temp[] = $value['task'];
}
$array[$value['employee']] = array_unique($temp);
}
return $array;
}
Add a conditional to the code to add the element if it does not already exist.
function Job($conn) {
$array = array();
foreach(array_unique($_SESSION['ROLES']) as $value)
{
$sql="SELECT employee,task FROM table WHERE id={$value} AND employee=24";//echo($sql);
$result = $conn->executeSQL($sql);
foreach($result as $value)
{
if ( ! in_array($value['task'], $array[$value['employee']]) )
$array[$value['employee']][] = $value['task'];
}
}
return $array;
}
I have the variable $request. If i do vardump($request), I get the output of:
array(7) {
["controller"]=> string(5) "index"
["action"]=> string(5)"index"
["module"]=> string(7) "default"
[2]=> array(8) {
["g_goal_list_id"]=> string(3) "127"
["textgoal"]=> string(9) "eats food"
["task_0"]=> string(1) "0"
["value_0"]=> string(5) "pukes"
["task_1"]=> string(1) "0"
["value_1"]=> string(0) ""
["task_2"]=> string(1) "0"
["value_2"]=> string(0) ""
}
[3]=> array(10) {
["g_goal_list_id"]=> string(3) "128"
["textgoal"]=> string(9) "goes home"
["task_0"]=> string(1) "0"
["value_0"]=> string(20) "but never comes back"
["task_1"]=> string(1) "0"
["value_1"]=> string(14) "stays home now"
["task_2"]=> string(1) "0"
["value_2"]=> string(0) ""
["task_3"]=> string(1) "0"
["value_3"]=> string(0) ""
}
["submit"]=> string(4) "Save"
["task"]=> string(1) "5"
}
which is all correct. However, I'm trying to use a foreach statment to grab values from the $request array and put them into a data array, and then submit that to the mysql db...
foreach($request as $currentrow){
//skips row if the field is empty
if(strlen($currentrow['value']) < 1)//need to make sure I've defined $currentrow['value']
continue;//skips row with empty field
//I only need to grab the value/list_id/account_id from the form
$data = array('value' => $currentrow['value'],
'g_goal_list_id' => $currentrow['g_goal_list_id'],
'account_id' => g_getAccountId(),
);
var_dump($data);
However, when I var_dump($data); my output looks like this:
array(3) { ["value"]=> string(1) "i" ["g_goal_list_id"]=> string(1) "i" ["account_id"]=> string(1) "1" }
array(3) { ["value"]=> string(1) "S" ["g_goal_list_id"]=> string(1) "S" ["account_id"]=> string(1) "1" }
array(3) { ["value"]=> string(1) "5" ["g_goal_list_id"]=> string(1) "5" ["account_id"]=> string(1) "1" }
The only thing that is correct in that var_dump($data) is the ["account_id"]
I'm thinking that my loop is incorrect, and I'm pretty bad with loops. Sooooo yeah, hopefully I included enough information. Thank you.
What you need is something like this:
foreach($request as $k=>$currentrow)
{
$hit = false;
$data = array();
// Only look for sub-arrays
if(is_array($currentrow))
{
foreach($currentrow as $k2=>$v2)
{
$explode = explode('_', $k2);
if($explode[0] === 'value') //need to make sure I've defined $currentrow['value'] regardless of suffix
{
$hit = true;
$data = array(
'value' => $v2,
'g_goal_list_id' => $currentrow[$k]['g_goal_list_id'],
'account_id' => g_getAccountId(),
);
continue;
}
}
}
if($hit === false)
{
continue;
}
var_dump($data);
}
This element: $currentrow['values'] does not exist (check your logs, you should see notices). Neither does $currentrow['g_goal_list_id'].
You loop through an array with all different elements, the first being a string, with value index. When you then take that string and subscribe that with values, it throws a warning, but then takes the first element.
To clarify, a some CLI code:
php > $a="abcd";
php > echo $a["foo"];
PHP Warning: Illegal string offset 'foo' in php shell code on line 1
a
If you want to loop over keys and values, do like this:
foreach($request as $key=>$value) {
}
That being said, I think a loop is not what you want, you do not have straighforward table-like data.
Huge thanks to #MonkeyZeus. I kept on getting an array that had the proper keys but all the values were null. Turns out I just needed to put my var_dump($data) inside of my loop, because when it was on the outside it was returning only the last array it looped thorough. On my form the last values it loops through were empty fields, that are meant for the user to add input. Also, I had to change 'g_goal_list_id' => $currentrow[$k]['g_goal_list_id'] to just 'g_goal_list_id' => $currentrow['g_goal_list_id']
foreach ($request as $k=> $currentrow) {
$hit = false;
$data = array();
if(is_array($currentrow)){
foreach ($currentrow as $k2 => $v2) {
$explode = explode('_', $k2); //blows off the suffix of the $key
//var_dump($explode);
//$explode=substr($explode,2);
//echo $k2;
//echo '******';
//echo $v2;
echo $explode[0];
echo '/';
if($explode[0] == 'value'){
//echo "[" . $currentrow['g_goal_list_id'] . "]";
$hit = true;
$data = array(
'value' => $v2,
'g_goal_list_id' => $currentrow['g_goal_list_id'],
'account_id'=> g_getAccountId(),
);
continue;
}
var_dump($data);
}
}
if ($hit === false){
continue;
}
break;
}
This is one of those that should be easy. I'm not even sure if "subset" is the right way to describe it.
My initial array looks like this:
array(3) { [0]=> array(5) { ["id"]=> string(1) "1" ["claim_id"]=> string(1) "1" ["price"]=> string(2) "50" ["date"]=> string(19) "2013-05-15 01:58:48" ["created"]=> string(19) "2013-05-15 01:58:48" } [1]=> array(5) { ["id"]=> string(2) "11" ["claim_id"]=> string(1) "1" ["price"]=> string(2) "45" ["date"]=> string(19) "2013-05-15 03:34:59" ["created"]=> string(19) "2013-05-15 03:37:01" } [2]=> array(5) { ["id"]=> string(2) "25" ["claim_id"]=> string(1) "1" ["price"]=> string(2) "50" ["date"]=> string(19) "2013-05-15 22:47:46" ["created"]=> string(19) "2013-05-15 22:52:02" } }
I'd ultimately like to end up with just the date and price values, swap them so that date is first in the array, reformat the date, and convert it to a json array that looks something like this:
[{"date":"Mar. 15","price":"50"},{"date":"Mar. 15","price":"45"},{"date":"Mar. 15","price":"50"}]
I ran a foreach statement to get at the data and reformat the date, then went out of my league with splice, unset, and other functions that took me in the wrong direction. Any ideas?
Try this
$array = array();
for($i = 0 ; $i<count($your_array);$i++) {
$a=array();
$a['date'] = $your_array[$i]['date'];
$a['price'] = date("F .j",strtotime($your_array[$i]["date"]));
array_push($array,$a);
}
json_encode($array);
Output
[{"date":"Mar. 15","price":"50"},{"date":"Mar. 15","price":"45"},{"date":"Mar. 15","price":"50"}]
Codepad
This should get you there
$ret = array();
foreach ($source as $rec){
$ret[] = array("date"=>$rec["date"], "price"=>$rec["price"]);
}
$json = json_encode($ret);
Create a quick function to create another array with only selected elements:
function datePriceToJson($array) {
$a = array();
foreach($array as $i => $a) {
$a[] = array("date" => $a['date'], "price" => $a['price']); //Creae a new array based on the one you want
}
return json_encode($a);
}
datePriceToJson($array);
You need to reconstruct array using correct foreach and the use json_encode to get the json
$req_array = array();
foreach($youArray as $value)
{
$temp = array();
$temp['date'] = $value['date'];
$temp['price'] = $value['price'];
$req_array[] = $temp;
}
$json = json_encode($req_array);
echo $json;
see demo
Hope it helps you
$infos =array(
array("id" =>"1","price"=>"50","date"=>"2013-05-15 01:58:48"),
array("id" =>"2","price"=>"55","date"=>"2013-06-15 01:58:48")
);
$i=0;
foreach ($infos as $info )
{
$infos[$i]["date"]= date("F .j",strtotime($info["date"]));
$i++;
}
echo json_encode($infos);
I have an array that groups different items by item type. I am grouping the result by category_id field. What I want is the output to be
item1 = 3
item2 = 2
My array looks like this if I do a var_dump()
array(2) {
["item1"]=>
array(3) {
[0]=>
string(1) "3"
[2]=>
string(1) "5"
[4]=>
string(1) "7"
}
["item2"]=>
array(2) {
[1]=>
string(1) "4"
[3]=>
string(1) "6"
}
}
Here is the code I am using:
$items = Item::where('order_id','=',$payload["orderId"])->get();
$itemsGrouped = [];
$count = 0;
foreach($items as $item){
$itemsGrouped[$item->category_id][$count] = $item->id;
$count++;
}
foreach($itemsGrouped as $grp){
echo key($itemsGrouped).'='.count($grp).'<br>';
};
And here is what I am currently getting. The count is working but not the $itemsGrouped key. It is duplicated.
item2=3<br>item2=2<br>
Change your code as below
foreach($itemsGrouped as $key => $grp){
echo $key.'='.count($grp).'<br>';
};
In order to use key() function, you need to traverse the array using next/current function
foreach($itemsGrouped as $key => $grp){
echo $key.'='.count($grp).'<br>';
};
key() function returns the current element's key, which is defined by an array's internal pointer. Obviously it always points to the last element.
$myarray = "Your array";
$count = array(); // create an empty array
foreach($myarray as $arr) {
foreach($arr as $a) {
$key = array_keys($a);
$count[$key[0]]++;
}
}
print_r($count);
array(3) {
[0]=>
array(4) {
["Field1"]=>
string(8) "80000007"
["Field2"]=>
string(16) "O70000006"
["Field3"]=>
string(0) ""
["Field4"]=>12345
string(0) ""
}
[1]=>
array(4) {
["Field1"]=>
string(8) "80000008"
["Field2"]=>
string(16) "O70000007"
["Field3"]=>
string(0) ""
["Field4"]=>78965
string(0) ""
}
[2]=>
array(4) {
["Field1"]=>
string(8) "80000009"
["Field2"]=>
string(16) "H80000006"
["Field3"]=>
string(0) ""
["Field4"]=>12345
string(0) ""
}
}
I have the above array i want to store this items of array into another temp array and use it . Here is what iam doing
$arr_tmp = array();
foreach ($result['record'] as $key => $value){
$arr_tmp['Field1'] = $value['Field1'];
$arr_tmp['Field2'] = $value['Field2'];
$arr_tmp['Field3'] = $value['Field3'];
$arr_tmp['Field4'] = $value['Field4'];
}
when i do var_dump($arr_tmp). Iam getting only the last record in the array. I need the same result set in this $arr_tmp when using foreach loop so that i can add some more items to this array .
You've only created a single arr_tmp array, and overwrite the values on each loop iteration. Possibly you'd want something like:
$arr_tmp[] = array('Field1' => $value['Field1'], 'Field2' => $value['Field2'], etc...)
inside the loop instead.
But, unless I'm reading your original array wrong, this will simply re-create the original array with new keys, so that begs the question... why? Wouldn't it be easier to just do:
$arr_tmp = $original_array;
?
$arr_tmp = array();
foreach ($result['record'] as $key => $value){
$cur = array();
$cur['Field1'] = $value['Field1'];
$cur['Field2'] = $value['Field2'];
$cur['Field3'] = $value['Field3'];
$cur['Field4'] = $value['Field4'];
$arr_tmp[] = $cur;
}