Traverse non-numerical indexes of an array - php

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".

Related

Find duplicate elements in an array

I got an array of coins with many details, that looks partially like that:
array(360) {
["VEN/USDT"]=>
array(15) {
["tierBased"]=>
bool(false)
}
["id"]=>
string(7) "VENUSDT"
["symbol"]=>
string(8) "VEN/USDT"
["base"]=>
string(3) "VEN"
["quote"]=>
string(4) "USDT"
["lot"]=>
float(0.01)
["active"]=>
bool(true)
}
All I need is this part:
["id"]=>
string(7) "VENUSDT"
["symbol"]=>
string(8) "VEN/USDT"
["base"]=>
string(3) "VEN"
["quote"]=>
string(4) "USDT"
if "base" is more often than once in the entire array.
The final code was:
$base_array = array();
foreach ($markets as $key=>$value) {
echo "1. Key = " . $key . "\n";
foreach ($value as $key => $value) {
if ($key == "base") {
echo "Base = " . $value . "\n";
array_push($base_array, $value);
}
}
}
// Duplicates we need only!
$unique = array_unique($base_array);
$duplicates1 = array_diff_assoc($base_array, $unique);
$duplicates = array_unique($duplicates1);
var_dump($duplicates);

create php array using simpleXMLobject

I'm trying to get this array ($resdata) with object(SimpleXMLElement) into a php array:
$resdata =
array(59) {
[0]=> ...
[10]=> object(SimpleXMLElement)#294 (28) {
["reservation_id"]=> string(7) "8210614"
["event_id"]=> string(6) "279215"
["space_reservation"]=> array(2) {
[0]=> object(SimpleXMLElement)#344 (9) {
["space_id"]=> string(4) "3760"
["space_name"]=> string(9) "205"
["formal_name"]=> string(33) "Center" }
[1]=> object(SimpleXMLElement)#350 (9) {
["space_id"]=> string(4) "3769"
["space_name"]=> string(9) "207"
["formal_name"]=> string(32) "Right" } } }
}
I've tried:
$res = (array)$resdata;
$reservation = $res['reservation'];
$result = array();
foreach ($reservation as $key => $value){
$res = array($value);
$spid = $res[0]->space_reservation->space_id;
echo $value->event_id."<br />";
echo $spid."<br />";
}
This only outputs the first space_id and I need to get all the space_ids within "space_reservation" array. Not all records will have multiple space_ids. Any help pointing me in the right direction is appreciated. Not sure if I should use xpath but I need to re-write my foreach statement regardless.
I was hoping to be able to literally convert all references to "object(SimpleXMLElement)#_ (#)" to "array(#)"
[10]=> array (28) {
["reservation_id"]=> string(7) "8210614"
["event_id"]=> string(6) "279215"
["space_reservation"]=> array(2) {
[0]=> array (9) {
["space_id"]=> string(4) "3760"
["space_name"]=> string(9) "205"
["formal_name"]=> string(33) "Center" }
[1]=> array (9) {
["space_id"]=> string(4) "3769"
["space_name"]=> string(9) "207"
["formal_name"]=> string(32) "Right" } } }
}
the function in my cakephp 1.3 controller is this:
$xml = simplexml_load_string($string);
$this->data['events']= $xml->children();
$resdata = $this->data['events'];
$this->set('resdata',$resdata);
I think this should do what you are looking for:
foreach ($resdata as $res) {
echo $res->event_id . '<br />';
foreach ($res->space_reservation as $reservation) {
echo $reservation->space_id . '<br />';
}
}
Googled it and found a general solution for any SimpleXMLElement to array conversion:
function xml2array($xml) {
$arr = array();
foreach ($xml as $element) {
$tag = $element->getName();
$e = get_object_vars($element);
if (!empty($e)) {
$arr[$tag] = $element instanceof SimpleXMLElement ? xml2array($element) : $e;
}
else {
$arr[$tag] = trim($element);
}
}
return $arr;
}

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;
}
}

PHP sequential foreach

Guys i've got an array thats like this:
array(3) {
[2]=>
array(1) {
["name"]=>
array(2) {
[0]=>
string(13) "row1"
[1]=>
string(13) "row3"
}
}
[5]=>
array(1) {
["name"]=>
array(2) {
[0]=>
string(15) "row1"
[1]=>
string(15) "row3"
}
}
[3]=>
array(1) {
["name"]=>
array(2) {
[0]=>
string(13) "row1"
[1]=>
string(13) "row3"
}
}
What i want to achieve is make foreach loop the 0 elements (row1) and then loop through 1 (row3) and go on like this. Is there a way to do that?
You could try to rebuild the array:
$rows = array();
foreach($array as $subarray)
foreach($subarray as $key => $value)
$rows[$key][] = $value;
At this point al the same subelements from the array are together in a new array, and now you can easy loop over a subelement:
foreach($rows as $key => $value)
echo 'processing row: ' . $key ' with value ' . $value;
I found a different approach to this problem, the JvdBeg solution is working wonderful, but if someone is stuck in a similar situations, this is how i did it:
$key = key($arr);
$keys = array_keys($arr);
for ($i=0;$i<sizeof($arr[$key]['index']);$i++) {
for($k=0;$k<sizeof($arr);$k++) {
$key = $keys[$k];
echo "\n";
}
}

read php array having string and object in sub array

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
//...
}

Categories