PHP combine_array produces false when element count is the same [duplicate] - php

This question already has answers here:
How to extract data from csv file in PHP
(13 answers)
Closed 1 year ago.
Apologies if this question is close to others. I have tried every solution to accomplish something simple with nothing but failure. :-(
I want the keys from array one to be assigned as keys to array two.
$demos_keys = array_keys($demos);
//$c = array_combine($demos_keys, $csvdata); produces "FALSE"
//$c = $demos_keys + $csvdata; simply adds the arrays but doesn't assign keys
So then I tried to loop through each element to assign the keys manually - to no avail!
foreach ($csvdata as $row){
for($i = 0; $i<count($demo_keys); $i++) {
$csvdata[$demo_keys[$i]]=$row[$i];
}
}
demos_keys:
lastname":"lastname","email":"email","d1":"phone","d2":"status"
csvdata:
"Dryer,fdryer#email.com,Backfield,North\r","Harris,fharris#email.com,Corp,South\r",etc.
I feel the csvdata array is wonky somehow. Every thing say it is an array with about 1000 rows, but the carriage return at the end of the last element is troubling me. I thought I'd deal with it later.
What else can I try!? Thank you all for any contributions!

It looks like each row of your CSV data has not been parsed into separate variables (are you reading it from a file using fgets or file instead of fgetcsv?). So you need to split it before you can combine it with the keys from $demos_keys. Something like this should work:
$demos_keys = array("lastname","email","d1","d2");
$csvdata = array("Dryer,fdryer#email.com,Backfield,North\r","Harris,fharris#email.com,Corp,South\r");
$result = array();
foreach ($csvdata as $row) {
$data = explode(',', trim($row));
$result[] = array_combine($demos_keys, $data);
}
print_r($result);
Output:
Array
(
[0] => Array
(
[lastname] => Dryer
[email] => fdryer#email.com
[d1] => Backfield
[d2] => North
)
[1] => Array
(
[lastname] => Harris
[email] => fharris#email.com
[d1] => Corp
[d2] => South
)
)
Demo on 3v4l.org

Related

Editing a poorly formatted JSON string in PHP

I have a site which I used JSON to save some data.
Here is how it saves data
{"1":{"english":{"grade":"7","time":"79"},"physics":{"grade":"3","time":"48"}}}
Note: I know this is a poor way of doing it but I did it when I was not so vast!
The 1 is the user_id which changes according to the id of the user that takes an exam on the platform. The english, physics are the subjects this user took.
The maximum number of exam a user can take at a time is for so the json string will look like {"1":{"english":{"grade":"7","time":"79"},"physics":{"grade":"3","time":"48"},"maths":{"grade":"7","time":"79"},"chemistry":{"grade":"3","time":"48"}}}
First I think this is the best way to save the result as a JSON string
[{"subject":"english","grade":"7","time":"79"}, {"subject":"physics", "grade":"3","time":"48"}}]
My problem is that I want to use PHP to work on the former on. I have done some few stripping of the string and I'm left with this {"english":{"grade":"7","time":"79"},"physics":{"grade":"3","time":"48"}}
I tried this chunk
$JSONResult = json_decode($aScore->result);
foreach ($JSONResult as $subjectKey => $aSubject)
{
foreach ($aSubject as $theResult)
{
$userResult = '
Subject: **This is what I've not been able to get**
Grade: '.$theResult->grade.'
Time: '.$theResult->time.'
';
}
}
I tried $aSubject->subjectKey to get the associative key value from the first foreach statement but it did not work
Any help?
Added: Please leave comments about the way the JSON string was stored. I'd love to learn.
You don't need the inner loop. Each subject is just a single object, not an array. And the subject key is just $subjectKey, it's not a part of the object.
$JSONResult = json_decode($aScore->result, true); // to get an associative array rather than objects
foreach ($JSONResult as $subjectKey => $aSubject) {
$userResult = "
Subject: $subjectKey
Grade: {$aSubject['grade']}
Time: {$aSubject['time']}
";
}
DEMO
You could use the second argument to json_decode!
It changes your $JSONResult from stdClass to an associative Array!
Which means you can do something like this:
$str = '{"1":{"english":{"grade":"7","time":"79"},"physics":{"grade":"3","time":"48"}}}';
$result = json_decode($str, true); // Put "true" in here!
echo "<pre>".print_r($result, true)."</pre>"; // Just for debugging!
Which would output this:
Array
(
[1] => Array
(
[english] => Array
(
[grade] => 7
[time] => 79
)
[physics] => Array
(
[grade] => 3
[time] => 48
)
)
)
And in order to loop through it:
foreach ($result as $idx => $exams) {
echo $exams['english']['grade']."<br>";
echo $exams['physics']['grade']."<br>";
}
Which would output this:
7
3
Update
Without knowing the containing arrays data (Based on the example above)
$exams will be an Array (which could contain any sort of information):
Array
(
[english] => Array
(
[grade] => 7
[time] => 79
)
[physics] => Array
(
[grade] => 3
[time] => 48
)
)
If you want to loop through $exams:
foreach ($result as $idx => $exams) {
foreach ($exams as $subject => $info) {
echo $info['grade']."<br>";
}
}
This would produce the same output as the above example, without needing to know a subject name!

Multidimesional array pointers

I'm building an array piece by piece following a specific pattern.
For example, I have this string <val0=0, val1=<val2=2, val3=<val4=4>>, val5=5> and I need to translate it to an associative array. So every time I find < I have to create a new array and store the following elements until the next >.
The string above should result in something like this:
Array
(
[val0] => 0
[val1] => Array
(
[val2] => 2
[val3] => Array
(
[val4] => 4
)
)
[val5] => 5
)
Everything is working fine for non-multidimensional arrays using str_split to break the string in pieces and iterating over them in a for loop but I'm having difficulties to find a workaround every time there is a nesting array in the string.
What I need is a way to have a pointer to the last created array inside the main array.
Is there a way to store an array pointer reference in a variable so I could do this:
print_r($MULTIARRAY['val1']['val3']);
// prints: array()
$pointer = pointer($MULTIARRAY['val1']['val3']);
$pointer[] = 'AAA';
$pointer[] = 'BBB';
print_r($MULTIARRAY['val1']['val3']);
// prints: array(
// [0] => AAA
// [1] => BBB
//)
Here you go, it's called reference
$a[1][22] = array();
$pointer = &$a[1][22];
$pointer[] = 3;
$pointer[] = 4;
print_r($a);

PHP Array_unique value error in while loop

This is my PHP script for getting plan
This is my table
plan
3|6
6|12
3|12
and
<?php
$tenure="SELECT plan from ".TABLE_TYBO_EMI_GATEWAY;
$t_result=dbQuery($tenure);
while($t_data=mysql_fetch_assoc($t_result))
{
$arrayVal=explode("|",$t_data['plan']);
print_r(array_unique($arrayVal));
}
?>
and I got the result is
Array ( [0] => 3 [1] => 6 ) Array ( [0] => 6 [1] => 12 )
Here I want 3,6,12 only. What is the problem in my script
before your while loop add this line:
$arrayVal = array();
and replace $arrayVal=explode("|",$t_data['plan']); with $arrayVal=array_merge($arrayVal, explode("|",$t_data['plan']));
$tenure="SELECT plan from ".TABLE_TYBO_EMI_GATEWAY;
$t_result=dbQuery($tenure);
$arrayVal = array();
while($t_data=mysql_fetch_assoc($t_result))
{
$arrayVal = array_merge($arrayVal, explode("|",$t_data['plan']));
}
print_r(array_unique($arrayVal));
Note: When using array_merge with associated arrays, it will overwrite values for same keys, but when using numeric keys array_merge will not overwrite them instead append as new values.

php reassign array contents [duplicate]

This question already has answers here:
Transposing multidimensional arrays in PHP
(12 answers)
Closed 1 year ago.
any particular function or code to put this kind of array data
ori [0] => 43.45,33,0,35 [1] => 74,10,0,22 [2] => 0,15,0,45 [3] => 0,0,0,340 [4] => 12,5,0,0 [5] => 0,0,0,0
to
new [0] => 43.45,74,0,0,12,0 [1] => 33,10,15,0,5,0 [2] => 0,0,0,0,0,0, [3] => 35,22,45,340,0,0
As you can see, the first value from each ori are inserted into the new(0), the second value from ori are inserted into new(1) and so on
If $ori is an array of arrays, this should work:
function transpose($array) {
array_unshift($array, null);
return call_user_func_array('array_map', $array);
}
$newArray = transpose($ori);
Note: from Transposing multidimensional arrays in PHP
If $ori is not an array of arrays, then you'll need to convert it first (or use the example by Peter Ajtai), like this:
// Note: PHP 5.3+ only
$ori = array_map(function($el) { return explode(",", $el); }, $ori);
If you are using an older version of PHP, you should probably just use the other method!
You essentially want to transpose - basically "turn" - an array. Your array elements are strings and not sub arrays, but those strings can be turned into sub arrays with explode() before transposing. Then after transposing, we can turn the sub arrays back into strings with implode() to preserve the formatting you want.
Basically we want to go through each of your five strings of comma separated numbers one by one. We take each string of numbers and turn it into an array. To transpose we have to take each of the numbers from a string one by one and add the number to a new array. So the heart of the code is the inner foreach(). Note how each number goes into a new sub array, since $i is increased by one between each number: $new[$i++][] =$op;
foreach($ori as $one) {
$parts=explode(',',$one);
$i = 0;
foreach($parts as $op) {
$new[$i++][] =$op;
}
}
$i = 0;
foreach($new as $one) {
$new[$i++] = implode(',',$one);
}
// print_r for $new is:
Array
(
[0] => 43.45,74,0,0,12,0
[1] => 33,10,15,0,5,0
[2] => 0,0,0,0,0,0
[3] => 35,22,45,340,0,0
)
Working example

Compare two arrays in php

I have two arrays named rows and contacts.
The first array rows is like :
Array
(
[0] => email#gmail.com
[1] => test#gmail.com
[2] => tester#gmail.com
[3] => vin#gmail.com
)
The second array contacts is as :
Array
(
[test#gmail.com] => test#gmail.com
[ram#gmail.com] => Ram
[vin#gmail.com] => Vinay
[man_test#yahoo.com] => Manoj
[homan#rediffmail.com] => Homan
)
What I want is the contacts array to be as :
Array
(
[ram#gmail.com] => Ram
[man_test#yahoo.com] => Manoj
[homan#rediffmail.com] => Homan
)
Edit
I tried some functions like array_diff(), array_keys() etc. but they are not giving me the desired output, may be I am not able to use them correctly....!
I don't want to use loop for this purpose because the given arrays are only sample data but in real they are very huge.
Please help.....
Thanks in Advance.....
Another way:
$contacts = array_diff_key($contacts, array_flip($rows));
Assuming I understand the question correctly, you could do that:
for ($i = 0; $i < count($rows); $i++) {
$s = $rows[$i];
unset($contacts[$s]);
}
foreach ($contacts as $email => $name) {
if (!in_array($email, $rows)) {
$contact[$email] = $name;
}
}
The new array is $contact, not $contacts, as your question asked for before you edited it.
As Felix Kling and Dan Grossman's answers will work on the examples you have shown, you probably have whitespace issues like newlines in your data, especially if you have extracted it from a file. So, extending Felix's answer:
$contacts = array_diff_key(array_map('trim', $contacts), array_flip(array_map('trim', $rows)));
You could probably make it more efficient by constructing your data correctly in the first place, but this should do the trick.
http://codepad.org/RIvLbyJy

Categories