Reputation: 709
I have an array of arrays like this:
[0]
{
Array[0] { First_Name => "john" }
Array[1] { Last_Name => "smith" }
Array[2] { Job => "Worker Ant" }
}
[1]
{
Array[0] { First_Name => "jane" }
Array[1] { Last_Name => "smith" }
}
etc. Let's call it peopleArray
;
I also have an array of keys such as "First_Name, Last_Name"
that would match the keys in the above examples. I'll call it headingArray
.
I want to echo out peopleArray
seperated by commas like this:
"'john', 'smith', 'Worker Ant'"
'jane','smith',''
And have the values without keys in the headingArray
be just an empty string.
I've been trying something like this:
for($i=0; $i < count($headingArray); $i++){
foreach($peopleArray as $row){
foreach($row as $data){
if(key($data) == $headingArray[$i]){
echo '"'.current($data).'",';
}
}
}
//die();
echo "\r\n";
}
Where I loop through each header and try to match up the values, but it clearly doesn't work.
There must be a simpler way of doing this.
Can anyone help me out/point me in the right direction? I've been pounding my brain on this for hours.
Edit: I've come up with this. It echoes all the values I need, but does some weird thing with skipping the ones that don't exist:
foreach($peopleArray as $person) {
$prevKey = array();
$numItems = count($person);
$i = 0;
foreach($person as $heading) {
foreach($person as $key => $value) {
if(key($value) == $heading){
echo '"'.str_replace(',',' ',current($value)).'",';
$prevKey[] = key($value);
break;
} else if(in_array(key($value), $prevKey)) {
} else {
echo '"",';
}
}
//die(var_dump($prevKey));
$i++;
}
echo "\r\n";
}
I need it to return a blank string if it doesn't exist.
Upvotes: 1
Views: 210
Reputation: 1442
Something like this should do:
foreach($peopleArray as $person) {
foreach($person as $keyValue) {
foreach($keyValue as $key => $value) {
if(in_array($key, $headingArray)) {
echo '"'.$value.'", ';
} else {
echo '"", ';
}
}
}
echo "\r\n";
}
Upvotes: 0
Reputation:
Try to use objects:
<?php
class Worker
{
//without getters/setters, just idea
private $first_name;
private $last_name;
private $job;
public function __toString()
{
return "'".implode("', '", get_object_vars($this))."'";
}
}
//let's assume we have array of Worker objects
foreach ($Workers as $Worker)
{
print $Worker.PHP_EOL;
}
Upvotes: 1
Reputation: 41533
foreach($peopleArray as $p)
{
foreach($i=0,$l=count($headingArray);$i<$l;$i++)
{
$value = isset($p[$headingArray[$i]]) ? $p[$headingArray[$i]] : '';
$comma = $i<($l+1) ? ',' : '';
echo '"' . $value . '"', $comma;
}
echo "\r\n";
}
Upvotes: 0