read php array having string and object in sub array - php

I have the following output sing var_dump.. How do I read the value of 'transferfrom' for each array ? The 'ST00576' and 'OT01606' are dynamic values.It can change on the subsequence arrays.
string(19) "TB3360 7D B 70"
array(2) {
["ST00576"]=>
object(stdClass)#1 (13) {
["transferfrom"]=>
int(102)
["transferto"]=>
int(66)
["BR_ID"]=>
int(102)
}
["OT01606"]=>
object(stdClass)#2 (13) {
["transferfrom"]=>
int(102)
["transferto"]=>
int(66)
["BR_ID"]=>
int(66)
}
}
string(19) "TB3360 BL A 75"
array(2) {
["ST00576"]=>
object(stdClass)#3 (13) {
["transferfrom"]=>
int(102)
["transferto"]=>
int(66)
["BR_ID"]=>
int(102)
}
["OT01606"]=>
object(stdClass)#4 (13) {
["transferfrom"]=>
int(102)
["transferto"]=>
int(66)
["BR_ID"]=>
int(66)
}
}

Not sure exactly what you need, but this will pick the 'transferfrom' item out of each array entry and return an array with the same keys but strings as values.
$arr = array_map(function($item) {
return $item->transferfrom;
}, $arr);
Or:
function pick_transferfrom($item)
{
return $item->transferfrom;
}
$arr = array_map('pick_transferfrom', $arr);
Result (shortened):
['OT01606' => 102, 'ST00576' => 102];
Or you can just iterate:
foreach ($arr as $key => $item) {
$transferfrom = $item->transferfrom;
// do whatever you like with $transferfrom and $key
}

foreach($arrays as $arr){
$transferfrom = $arr['transferfrom'];
//here you do whatever you want with $arr
//...
}

Related

how to use explode for an array of objects

I have an array like that:
array(5) {
["code"]=>
int(1)
["messageError"]=>
string(27) "La typologie est incorrecte"
["model"]=>
string(3) "lot"
["grp_regles"]=>
array(1) {
[0]=>
array(1) {
[0]=>
array(3) {
["champ"]=>
string(21) "lot_surface_habitable"
["comparaison"]=>
string(7) "between"
["valeurAttendue"]=>
array(2) {
[0]=>
int(16)
[1]=>
int(40)
}
}
}
}
["prerequis"]=>
array(2) {
[0]=>
array(3) {
["champ"]=>
string(6) "typ_id"
["comparaison"]=>
string(1) "="
["valeurAttendue"]=>
int(1)
}
[1]=>
array(3) {
["champ"]=>
string(22) "tranche.fus.fup.fup_id"
["comparaison"]=>
string(1) "="
["valeurAttendue"]=>
int(1)
}
}
}
I want to do a foreach in "prerequis":
$modelRetrieve = $this->retrieveModel($model);
$modelFind = $modelRetrieve::find($id);
$arrayError=[];
$query = '';
$path = storage_path() . "/json/controle.json";
$json = file_get_contents($path);
foreach (json_decode($json,true) as $key => $value) {
$test = true;
var_dump($value);
if($value['model'] === $model ){
foreach ($value['prerequis'] as $key => $value2) {
if( $test && $modelFind[$value2['champ']] == (int)$value2["valeurAttendue"] )
{
$test = true;
}
}
}
}
I need in second foreach to use in $value2['champ'] where $value2['champ'] is "tranche.fus.fup_id. So I need to explode that to have ['tranche']['fus']['fup_id'].
How to use explode with that ?
thanks everyone :)
you can use laravel data_get helper:
data_get($value2, $value2['champ'])
To nest the $segments of the string starting with the innermost item of the result, we have to array_reverse() the $segments so we can loop over it and wrap each iteration's result with another array level in the next iteration until we looped through the whole $segments array.
$exploded = array_reduce(array_reverse(explode('.', $value2['champ'])), function($res, $segment) {
return [ $segment => $res ];
}, []);

How to group a multidimensional array by multiple subarray values?

I checked this question and answers:
How to group a multidimensional array by a particular subarray value?
He wanted to group results by 'level'. But how would you do it to group it by 'level' first and then by 'type'?
Its pretty straight forward. Loop through $items array. Get each item's level and type and if they are not set yet, initialize them with an empty array. Then just push the "cust" value into the array.
I have given the code below.
I am assuming "$items" is an array which contains the input.
$g = [];
foreach($items as $k => $v) {
$l = $v["level"];
$t = $v["type"];
$c = $v["cust"];
if(!isset($g[$l])) {
$g[$l] = [];
}
if(!isset($g[$l][$t])) {
$g[$l][$t] = [];
}
$g[$l][$t][] = [
"cust" => $c
];
}
var_dump($g);
The output of this code would be like below:
array(3) {
[1]=>
array(1) {
["standard"]=>
array(2) {
[0]=>
array(1) {
["cust"]=>
string(6) "XT8900"
}
[1]=>
array(1) {
["cust"]=>
string(6) "XT8944"
}
}
}
[3]=>
array(1) {
["premier"]=>
array(2) {
[0]=>
array(1) {
["cust"]=>
string(6) "XT8922"
}
[1]=>
array(1) {
["cust"]=>
string(6) "XT8816"
}
}
}
[7]=>
array(1) {
["standard"]=>
array(1) {
[0]=>
array(1) {
["cust"]=>
string(6) "XT7434"
}
}
}
}
[P.S.]: You can also use sort to solve this problem easily. That's another way of solving this problem.

Remove/unset every other key in multidimensional array but preserve keys

I have a long multidimensional array with timestamps as keys which contain arrays of values. Something like this but with more timestamps:
array(3) {
[1502609400]=>
array(2) {
["Item1"]=>
array(1) {
["PRICE"]=>
float(100)
}
["Item2"]=>
array(1) {
["PRICE"]=>
float(50)
}
}
[1502611200]=>
array(2) {
["Item1"]=>
array(1) {
["PRICE"]=>
float(200)
}
["Item2"]=>
array(1) {
["PRICE"]=>
float(150)
}
}
[1502613000]=>
array(2) {
["Item1"]=>
array(1) {
["PRICE"]=>
float(500)
}
["Item2"]=>
array(1) {
["PRICE"]=>
float(250)
}
}
How can I remove every every second array of the array without losing the keys as timestamp? So I end up with this:
array(3) {
[1502609400]=>
array(2) {
["Item1"]=>
array(1) {
["PRICE"]=>
float(100)
}
["Item2"]=>
array(1) {
["PRICE"]=>
float(50)
}
}
[1502613000]=>
array(2) {
["Item1"]=>
array(1) {
["PRICE"]=>
float(500)
}
["Item2"]=>
array(1) {
["PRICE"]=>
float(250)
}
}
If I use a for loop and unset every second key I lose all the keys and end up with 0, 1, 2 etc. instead of the timestamp.
In a loop, check for index and unset every second element:
You can use custom $index variable, like this:
$index = 0; // points to first element
foreach ($array as $key => $value) {
if ($index % 2 != 0) { //check for un-even
unset($array[$key]);
}
$index++; // move pointer to next element
}
$i=1 // where the key to remove
$x=0; //loop to determine the key position
foreach ($array as $key=>$value){
if($x==$i){
unset($array[$key]);
}
$x++;
}
In that kind of case, a simple foreach can be more efficient perfwise than a standard function :
foreach ($array as $key => $val) {
if (array_key_exists('Item2', $val)) {
unset($val['Item2']);
}
}

PHP Error: Undefined offset error within foreach loop

I have a csv file which I am trying to turn into a different structured array. First, I turn it into an array named all_data() constructed like this:
$data = file_get_contents($id . '.csv');
$data_array = explode("\n", $data);
foreach($data_array AS $data){
$all_data[] = explode("\t", $data);
}
results look like this:
array(5) {
[0]=>
array(2) {
[0]=>
string(10) "2012-11-14"
[1]=>
string(2) "10"
}
[1]=>
array(2) {
[0]=>
string(10) "2012-11-14"
[1]=>
string(2) "10"
}
[2]=>
array(2) {
[0]=>
string(10) "2012-11-14"
[1]=>
string(2) "10"
}
[3]=>
array(2) {
[0]=>
string(10) "2012-11-14"
[1]=>
string(2) "10"
}
[4]=>
array(1) {
[0]=>
string(0) ""
}
}
And then I turn it into im_arr() with the following code:
foreach($all_data as $key => $value){
$im_arr[$key][$value[0]] = $value[1];
}
The results:
array(5) {
[0]=>
array(1) {
["2012-11-14"]=>
string(2) "10"
}
[1]=>
array(1) {
["2012-11-14"]=>
string(2) "10"
}
[2]=>
array(1) {
["2012-11-14"]=>
string(2) "10"
}
[3]=>
array(1) {
["2012-11-14"]=>
string(2) "10"
}
[4]=>
array(1) {
[""]=>
NULL
}
}
And then, finally another foreach loop gives me the results I am looking for:
foreach ($im_arr as $val) {
foreach ($val as $key => $val2) {
$im_data[$key]=$val2;
}
}
With the result for im_data() being:
array(2) {
["2012-11-14"]=>
string(2) "10"
[""]=>
NULL
}
Which would be perfect, since the array im_data() is exactly what I would like to get out of all_data(). However, when I am trying to put this code in another part of the program it doesn't work, and I am thinking it might be because of the warnings I receive:
"PHP Notice: Undefined offset: 1 in ... on line 93"
Line 93 corresponds to this line:
$im_arr[$key][$value[0]] = $value[1];
Here is the complete part of the code:
$all_data = array();
$im_arr=array();
$data = file_get_contents($id . '.csv');
$data_array = explode("\n", $data);
foreach($data_array AS $data){
$all_data[] = explode("\t", $data);
}
foreach($all_data as $key => $value){
$im_arr[$key][$value[0]] = $value[1]; //the line for the error
}
$im_data=array();
foreach ($im_arr as $val) {
foreach ($val as $key => $val2) {
$im_data[$key]=$val2;
}
}
var_dump($im_data);
I know there are many many questions posted for this same error, but I couldn't figure out the problem with this particular piece of code.
This is the problem:
[4]=>
array(1) {
[0]=>
string(0) ""
}
Just check that the data is set, and isn't empty before adding them to $im_arr:
foreach ($all_data as $key => $value) {
if (isset($value[0]) && isset($value[1]) && !empty($value[0]) && !empty($value[1])) {
$im_arr[$key][$value[0]] = $value[1];
}
}
For every foreach i would pre-check if the first argument is an array
For instance ;
//Just add line below for every foreach (and add any required else statement if needed)
if(is_array($im_arr))
foreach ($im_arr as $val) {
if(is_array($val))
foreach ($val as $key => $val2) {
$im_data[$key]=$val2;
}
}

Traverse non-numerical indexes of an array

Think I'm missing a basic concept. I want to generate html by traversing through a few different arrays of data. They don't use numbers as indexes so numerical looping doesn't work. I cant figure out how to use a foreach() here either. How can I traverse $price and $description when the indexes aren't numbers?
Sample:
$traverser= 0;
while($traverser < $number_of_records)
{
print $traverser . " - " . $price[$traverser] . "<br />";
print $description[$traverser];
$traverser++;
}
Partial Sample of the Array Structure:
object(phpQueryObject)#2799 (13) { ["documentID"]=> string(32) "1d62be942498df890cab4ccb78a007a2" ["document"]=> &object(DOMDocument)#3 (0) { } ["charset"]=> &string(5) "utf-8" ["documentWrapper"]=> &object(DOMDocumentWrapper)#2 (17) { ["document"]=> &object(DOMDocument)#3 (0) { } ["id"]=> string(32) "1d62be942498df890cab4ccb78a007a2" ["contentType"]=> string(9) "text/html" ["xpath"]=> &object(DOMXPath)#4 (0) { } ["uuid"]=> int(0) ["data"]=> array(0) { } ["dataNodes"]=> array(0) { } ["events"]=> array(0) { } ["eventsNodes"]=> array(0) { } ["eventsGlobal"]=> array(0) { } ["frames"]=> array(0) { } ["root"]=> &object(DOMElement)#5 (0) { } ["isDocumentFragment"]=> &bool(true) ["isXML"]=> bool(false) ["isXHTML"]=> bool(false) ["isHTML"]=> bool(true) ["charset"]=> &string(5) "utf-8" } ["xpath"]=> &object(DOMXPath)#4 (0) { } ["elements"]=> array(560) { [0]=> object(DOMElement)#2239 (0) { } [1]=> object(DOMElement)#2240 (0) { } [2]=> object(DOMElement)#2241 (0) { } [3]=> object(DOMElement)#2242 (0) { } [4]=> object(DOMElement)#2243 (0) { } [5]=> object(DOMElement)#2244 (0) { } [6]=> object(DOMElement)#2245 (0) { } [7]=> object(DOMElement)#2246 (0) { } [8]=> object(DOMElement)#2247 (0) { }
Since it looks like you need the array keys as well, since you're referencing multiple different arrays, you want the $a as $k => $v syntax for foreach:
foreach($description as $key => $desc)
{
print $key . " - " . $price[$key] . "<br />";
print $desc;
}
You can take your pic as to how you want to iterate them:
<?php
$ary = array( // demo array
'apple' => 'Apple',
'orange' => 'Orange',
'grape' => 'Grape'
);
// show the structure
var_dump($ary); echo "\r\n";
// use a foreach with the key and value
foreach ($ary as $key => $val)
printf("%s => %s\r\n", $key, $val);
echo "\r\n";
// just get the raw keys
$keys = array_keys($ary);
var_dump($keys); echo "\r\n";
output:
array(3) {
["apple"]=>
string(5) "Apple"
["orange"]=>
string(6) "Orange"
["grape"]=>
string(5) "Grape"
}
apple => Apple
orange => Orange
grape => Grape
array(3) {
[0]=>
string(5) "apple"
[1]=>
string(6) "orange"
[2]=>
string(5) "grape"
}
There's always array_map & array_walk.
I'm not sure I get the question, but it's really as simple as:
<?php
$array = array('foo', 'bar');
foreach ($array as $element) {
echo "{$element}\n";
}
This should output "foo" and "bar".

Categories