multidimensional irregular array to CSV in PHP - php

First of all I know there are many threads dedicated to this topic but I didn't found/figured out the right solution for my problem, sorry if I missed something.
So I got an array that looks like this:
Array
(
[0] => id1
[1] => Array
(
[0] => Url1
)
[2] => id2
[3] => no url found
[4] => id3
[5] => Array
(
[0] => url3.1
[1] => url3.2
[2] => url3.3
)
)
and i want to build a csv looking like:
id1,url1
id2,no url found
id3,url3.1,url3.2,url3.3
tried with
foreach($array as $row){
fputcsv($csv, $row, ',');
}
but it grabs only the elements of the subarrays if they exist. How should I approach that? Thanks in advance!

I would suggest creating an intermediate array from the original one, which would have the desired structure, and then create the CSV output from that:
// Preprocess the array to get the format needed for the CSV output
for ($i = 0; $i < count($array); $i += 2) {
$result[] = is_array($array[$i+1])
? array_merge([$array[$i]], $array[$i+1])
: [$array[$i], $array[$i+1]];
}
foreach($result as $row){
fputcsv($csv, $row, ',');
}
See it run on eval.in.

Related

Getting Values from MultiDimensional array

My Array shown as follows:
Array
(
[0] => Array
(
[amount_id] => 1
[enquiry_id] => 1
[project_id] => 1
)
[1] => Array
(
[amount_id] => 4
[enquiry_id] => 4
[project_id] => 4
)
[2] => Array
(
[amount_id] => 5
[enquiry_id] => 5
[project_id] => 5
)
)
This Array can be increase. How can i get value of each 'amount_id' from this array? What function should i use? Can for each function will work?
Just try with:
$input = array( /* your data */ );
$output = array();
foreach ($input as $data) {
$output[] = $data['amount_id'];
}
You can use a one-liner array_walk() to print those..
array_walk($arr,function($v){ echo $v['amount_id']."<br>";});
Working Demo
Do like this in array_map or Use array_column for The version PHP 5.5 or greater
$outputarr= array_map(function($item){ return $item['amount_id'];},$yourarr);
print_r($outputarr);
Try the following, this is accessing the specific array - easier to debug later on and better speed:
$num=count($your_array);
for($i="0"; $i<$num; $i++)
{
echo $your_array[$i]['amount_id'];
}
you could loop until $i < count($your_array) but it means that the count will run in every loop, for high performance sites I wouldn't do it.
you could access a specific element in a 2D array by $your_array[$the_index]['amount_id'] or other index.

Calculation from specific array values in PHP

i have the following array written in PHP.
I need a way to print values by name, and if possible, do calculations with specific values (by looping through).
[MAIN] => Array
(
[FIRST] => Array
(
[0] => 500
[1] => 1000
[2] => 1500
)
[SECOND] => Array
(
[Name] => Nick
[State] => None
)
)
For example, by using the array above i'd like to print only the NAME of the "SECOND" array but without looping through every index (without using an index at all), and add each value of the "FIRST" array by looping throu them.
Thank you!
$result = 0;
foreach ($array['MAIN']['FIRST'] as $val) {
$result += $val;
}
echo $result;
The first question is like this:
echo $array['MAIN']['SECOND']['Name'];
You have an array of an array of an array so you have to dereference values as such.
The second one would look something like this:
$var = 0;
for($i = 0; $i < 3; $i++) {
$var += $array['MAIN']['FIRST'][$i];
}
echo $var;

PHP: Why missing values in associative array?

Can someone please put me out of my misery and explain why I'm missing the middle value when I try to push the results of a preg_match into another array? It's either something silly or a vast gap in my understanding. Either way I need help. Here is my code:
<?php
$text = 'The group, which gathered at the Somerfield depot in Bridgwater, Somerset,
on Thursday night, complain that consumers believe foreign meat which has been
processed in the UK is British because of inadequate labelling.';
$word = 'the';
preg_match_all("/\b" . $word . "\b/i", $text, $matches, PREG_OFFSET_CAPTURE);
$word_pos = array();
for($i = 0; $i < sizeof($matches[0]); $i++){
$word_pos[$matches[0][$i][0]] = $matches[0][$i][1];
}
echo "<pre>";
print_r($matches);
echo "</pre>";
echo "<pre>";
print_r($word_pos);
echo "</pre>";
?>
I get this output:
Array
(
[0] => Array
(
[0] => Array
(
[0] => The
[1] => 0
)
[1] => Array
(
[0] => the
[1] => 29
)
[2] => Array
(
[0] => the
[1] => 177
)
)
)
Array
(
[The] => 0
[the] => 177
)
So the question is: why am I missing the [the] => 29? Is there a better way? Thanks.
PHP arrays are 1:1 mappings, i.e. one key points to exactly one value. So you are overwriting the middle value since it also has the key the.
The easiest solution would be using the offset as the key and the matched string as the value. However, depending on what you want to do with the results a completely different structure might be more appropriate.
First you assign $word_pos["the"] = 29 and then you OVERWRITE IT with $word_pos["the"] = 177.
You don't overwrite The because indexes are case sensitive.
So maybe use an array of objects like this:
$object = new stdClass;
$object->word = "the"; // for example
$object->pos = 29; // example :)
and assign it to an array
$positions = array(); // just init once
$positions[] = $object;
alternatively you can assign an associative array instead of the object, so it would be like
$object = array(
'word' => 'the',
'pos' => 29
);
OR assign the way you do, but instead of overwriting, just add it to an array, like:
$word_pos[$matches[0][$i][0]][] = $matches[0][$i][1];
instead of
$word_pos[$matches[0][$i][0]] = $matches[0][$i][1];
so you get something like:
Array
(
[The] => Array
(
[0] => 0
)
[the] => Array
(
[0] => 29
[1] => 177
)
)
Hope that helps :)
What is happening actually :
when i=0,
$word_pos[The] = 0 //mathches[0][0][0]=The
when i=1
$word_pos[the] = 29
when i=3
$word_pos[the] = 177 //here this "the" key overrides the previous one
//so your middle 'the' is going to lost :(
Now an array based solution can be like this :
for($i = 0; $i < sizeof($matches[0]); $i++){
if (array_key_exists ( $matches[0][$i][0] , $word_pos ) ) {
$word_pos[$matches[0][$i][0]] [] = $matches[0][$i][1];
}
else $word_pos[$matches[0][$i][0]] = array ( $matches[0][$i][1] );
}
Now if you dump $word_pos the output should be :
Array
(
[The] => Array
(
[0] => 0
)
[the] => Array
(
[0] => 29 ,
[1] => 177
)
)
Hope that helps.
Reference : array_key_exist

Resetting keys of resultant array of array_diff()

In my application I am using array_diff function as -
$aDeleteCountryCodes = array_diff($aCurrentCountryCodes, $aNewCountryCodes);
Now what happens is, the resultant array, $aDeleteCountryCodes, some times comes as
Array
(
[2] => 213
)
and some times
Array
(
[2] => 213
[3] => 355
)
which messes my for loop that I use to delete records from database. For loop is like this-
for ($i=0; $i <= count($aDeleteCountryCodes); $++)
{
// Delete record $aDeleteCountryCodes[$i]
}
what I want is the array to come as -
Array
(
[0] => 213
)
Array
(
[0] => 213
[1] => 355
)
so that the looping becomes easier. I hope I made it clear. How can I do this ?
Use array_values.
Use foreach instead of "manual for loops."
Rather than reset the keys, it's preferable to just iterate over the existing keys:
foreach ($aDeleteCountryCodes as $key => $value) {
// delete goes here.
}
Use array_values(array_diff($aCurrentCountryCodes, $aNewCountryCodes));
You can just get the values out into a new array:
$aDeleteCountryCodes = array_values($aDeleteCountryCodes) //Keys resetted.

Counting distinct values in a multidimensional array

I have an array that looks like the one below. I'm trying to group and count them, but haven't been able to get it to work.
The original $result array looks like this:
Array
(
[sku] => Array
(
[0] => 344
[1] => 344
[2] => 164
)
[cpk] => Array
(
[0] => d456
[1] => d456
)
)
I'm trying to take this and create a new array:
$item[sku][344] = 2;
$item[sku][164] = 1;
$item[cpk][d456] = 1;
I've gone through various iterations of in_array statements inside for loops, but still haven't been able to get it working. Can anyone help?
I wouldn't use in_array() personally here.
This just loops through creating the array as it goes.
It seems to work without needing to first set the index as 0.
$newArray = array();
foreach($result as $key => $group) {
foreach($group as $member) {
$newArray[$key][$member]++;
}
}

Categories