I have a $string:
'Name Height Weight
John 177 142
Jill 156 123
Jacob 183 157'
And I'm turning it into an $array of the following structure:
Array (
[0] => Array (
['Name'] => 'John'
['Height'] => '177'
['Weight'] => '142'
)
[1] = > Array (
['Name'] => 'Jill'
['Height'] => '156'
['Weight'] => '123'
)
[2] = > Array (
['Name'] => 'Jacob'
['Height'] => '183'
['Weight'] => '157'
)
)
Using the following code:
$rows = explode("\n",$string); //creates an indexed array of rows as strings
$headers = explode("\t",$rows[0]); //creates an indexed array of headers as strings
$rows = array_slice($rows,1); //removes headers from $rows
$array = Array();
foreach($rows as $row) {
$array[] = array_combine($headers, explode("\t",$row)); //creates associative arrays for each row
}
However, I cannot access the associative arrays inside of the indexed $array
For example, this doesn't work:
echo $array[0]['Name'];
Even though echo implode(', ', array_keys($array[0])); gives:
Name, Height, Weight
I've tried many different ways of accessing the associative arrays inside of the indexed array, but with no luck. What am I doing wrong?
EDIT:
So,
$string = "Name Height Weight
John 177 142
Jill 156 123
Jacob 183 157";
Does not work, but
$string = "Name\tHeight\tWeight\nJohn\t177\t142\nJill\t156\t123\nJacob\t183\t157";
does...
So I suppose the question is: What's the difference? And how would I interpret the former string as the latter?
Your code does not produce that array structure but it can be fixed like this:
$string = 'Name Height Weight
John 177 142
Jill 156 123
Jacob 183 157';
$rows = explode("\n",$string); //creates an indexed array of rows as strings
$headers = preg_split("#\s+#",trim($rows[0], "\n\r\t ")); //creates an indexed array of headers as strings, by splitting by any white space
var_dump($headers);
$rows = array_slice($rows,1); //removes headers from $rows
$array = Array();
foreach($rows as $row) {
$array[] = array_combine($headers, preg_split("#\s+#",trim($row, "\n\r\t "))); //creates associative arrays for each row, by splitting by any white space
}
var_dump($array);
This produces output:
array(3) {
[0]=>
string(4) "Name"
[1]=>
string(6) "Height"
[2]=>
string(6) "Weight"
}
array(3) {
[0]=>
array(3) {
["Name"]=>
string(4) "John"
["Height"]=>
string(3) "177"
["Weight"]=>
string(3) "142"
}
[1]=>
array(3) {
["Name"]=>
string(4) "Jill"
["Height"]=>
string(3) "156"
["Weight"]=>
string(3) "123"
}
[2]=>
array(3) {
["Name"]=>
string(5) "Jacob"
["Height"]=>
string(3) "183"
["Weight"]=>
string(3) "157"
}
}
The main ideas are that you must trim evey row string by any additional whitespaces and to split by the longest whitespace sequence.
//Use following code it will work as your answer
$string='Name Height Weight
John 177 142
Jill 156 123
Jacob 183 157';
$rows = explode("\n",$string); //creates an indexed array of rows as strings
$headers = explode("\t",$rows[0]); //creates an indexed array of headers as strings
$headers=array_filter(explode(" ",$headers[0])); ///t convert to space and filter remove empty element
$rows = array_slice($rows,1); //removes headers from $rows
$array = Array();
foreach($rows as $row) {
$row=explode("\t",$row);
$row=array_filter(explode(" ",$row[0]));
$array[] = array_combine($headers,$row); //creates associative arrays for each row
}
//print_r($array);
echo $array[0]['Name'];
Related
Why are these two strings not equal?
I tried to get the same name so I can create a file, however I cannot get two strings equal to each other, even though I think both strings have the same value.
I uploaded var_dump output
any idea how to fix it?
$selectCategory = scandir($_SERVER['DOCUMENT_ROOT'].'/database/');
$cat = explode('.',$category);
print_r($cat);
print_r($selectCategory);
if($cat[0] == $selectCategory[2]){
echo " true";
}
else{
echo "no";
}
output:
Array ( [0] => bus [1] => php )
Array ( [0] => . [1] => .. [2] => bus [3] => fruit )
no
This is var_dump output
array(2) { [0]=> string(5) " bus" [1]=> string(3) "php" }
array(4) { [0]=> string(1) "." [1]=> string(2) ".." [2]=> string(3) "bus" [3]=> string(5) "fruit" }
no
As you can see from the var_dump output the items you are comparing are different lengths. There is a space and possibly a hidden character in the $cat one:
To trim all space and some other characters use this:
$cat = array_map('trim', $cat);
$selectCategory = array_map('trim', $selectCategory);
I am trying to explode the JSON file below with the 2 arrays but keep getting an output of..
Array
(
[0] =>
)
Array
(
[0] =>
)
What am I doing wrong?
[0]=>
array(2) {
["question_id"]=>
string(2) "88"
["weight"]=>
string(1) "5"
}
[1]=>
array(2) {
["question_id"]=>
string(2) "89"
["weight"]=>
string(1) "5"
$quest_id = $data["question_id"];
$quest_points = $data["weight"];
$quest_id_array = explode(" ,", $quest_id);
$quest_points_array = explode(" ,", $quest_points);
print_r($quest_id_array);
print_r($quest_points_array);
Assuming $data is the array you show at the top, it's not an array containing comma-separated strings. It's a 2-dimensional array, so you need to loop over it and push the values onto the new arrays.
$quest_id_array = [];
$quest_points_array = [];
foreach ($data as $val) {
$quest_id_array[] = $val['question_id'];
$quest_points_array[] = $val['weight'];
}
How can I split this string into two arrays in PHP? The string may have many items in it.
$str = "20x9999,24x65,40x5";
I need to get two arrays from this string:
$array1 = array(20,24,40);
$array2 = array(9999,65,5);
I've tried many implementations of preg_split, slice, regex. I can't get it done... I need help!
You can explode the string by commas, and then explode each of those values by x, inserting the result values from that into the two arrays:
$str = "20x9999,24x65,40x5";
$array1 = array();
$array2 = array();
foreach (explode(',', $str) as $xy) {
list($x, $y) = explode('x', $xy);
$array1[] = $x;
$array2[] = $y;
}
Alternatively, you can use preg_match_all, matching against the digits either side of the x:
preg_match_all('/(\d+)x(\d+)/', $str, $matches);
$array1 = $matches[1];
$array2 = $matches[2];
In both cases the output is:
Array
(
[0] => 20
[1] => 24
[2] => 40
)
Array
(
[0] => 9999
[1] => 65
[2] => 5
)
Demo on 3v4l.org
I guess with preg_split, we could do so:
$str = '20x9999,24x65,40x5';
$array1 = $array2 = array();
foreach (preg_split("/,/", $str, -1, PREG_SPLIT_NO_EMPTY) as $key => $value) {
$val = preg_split("/x/", $value, -1, PREG_SPLIT_NO_EMPTY);
array_push($array1, $val[0]);
array_push($array2, $val[1]);
}
var_dump($array1);
var_dump($array2);
Output
array(3) {
[0]=>
string(2) "20"
[1]=>
string(2) "24"
[2]=>
string(2) "40"
}
array(3) {
[0]=>
string(4) "9999"
[1]=>
string(2) "65"
[2]=>
string(1) "5"
}
Please help me to combine four arrays in one.
I have to compare main array keys and if the key of the secondaries arrays coincides, add them to the new array.
I tried to combine different php functions, but without the expected result and nothing relevant.
This is the main array.
[0] => Array
(
[1] => "Category1"
[2] => "Category2"
[3] => "Category3"
[4] => "Category4"
)
These are the secondaries arrays
[1] => Array
(
[1] "user_test_[1]" key 1 map to --> [1] Category1
[2] "user_test_[2]" key 2 map to --> [2] Category2
[3] "user_test_[3]" key 3 map to --> [3] Category3
[4] "user_test_[4]" key 4 map to --> [4] Category4
)
[2] => Array
(
2: "user_prod_[2]" key 2 map to --> [2] Category2
4: "user_prod_[4]" key 4 map to --> [4] Category4
)
[3] => Array
(
[3] "user_uat_[3]" key 3 map to --> [3] Category3
[4] "user_uat_[4]" key 4 map to --> [4] Category4
)
New array results in php format:
$array_result = array(
'Category1'=>array(
'user_test_[1]'
),
'Category2'=>array(
'user_test_[2]',
'user_prod_[2]'
),
'Category3'=>array(
'user_test_[3]',
'user_uat_[3]'
),
'Category4'=>array(
'user_test_[4]',
'user_prod_[4]',
'user_uat_[4]'
)
);
Main array in in php format:
$array_cat = array(1=>"Category1", 2=>"Category2", 3=>"Category3", 4=>"Category4");
These are the secondaries arrays in php fromat:
$array_usrtest = array(1=>"user_test_[1]", 2=>"user_test_[2]", 3=>"user_test_[3]", 4=>"user_test_[4]");
$array_usruat = array(3=>"user_uat_[3]", 4=>"user_uat_[4]");
$array_usrprod = array(2=>"user_prod_[2]", 4=>"user_prod_[4]");
Expected results
array{
["Category1"]=>array(1)
{
[0]=>"user_test_[1]"
}
["Category2"]=>array(2)
{
[0]=>"user_test_[2]"
[1]=>"user_prod_[2]"
}
["Category3"]=>array(3)
{
[0]=>"user_test_[3]"
[2]=>"user_uat_[3]"
}
["Category4"]=>array(3)
{
[0]=>"user_test_[4]"
[1]=>"user_prod_[4]"
[2]=>"user_uat_[4]"
}
}
Here is simple solution, which it's not very good, because it is solution for your specific values, but it is good start point and if you want, you can improve it:
<?php
$array_cat = array(1=>"Category1", 2=>"Category2", 3=>"Category3", 4=>"Category4");
$array_usrtest = array(1=>"user_test_[1]", 2=>"user_test_[2]", 3=>"user_test_[3]", 4=>"user_test_[4]");
$array_usruat = array(3=>"user_uat_[3]", 4=>"user_uat_[4]");
$array_usrprod = array(2=>"user_prod_[2]", 4=>"user_prod_[4]");
$result = [];
foreach ($array_cat as $k => $v) {
$result[$v] = []; // fill result array with categories
}
$values = array_merge($array_usrtest, $array_usruat, $array_usrprod); // merge arrays into one (all items)
foreach ($values as $k => $value) { // iterate over all values
preg_match('!\d+!', $value, $match); // get index in [index]
$result['Category' . $match[0]][] = $value; // append values to category
}
echo '<pre>';
var_dump($result);
Result:
array(4) {
["Category1"]=>
array(1) {
[0]=>
string(13) "user_test_[1]"
}
["Category2"]=>
array(2) {
[0]=>
string(13) "user_test_[2]"
[1]=>
string(13) "user_prod_[2]"
}
["Category3"]=>
array(2) {
[0]=>
string(13) "user_test_[3]"
[1]=>
string(12) "user_uat_[3]"
}
["Category4"]=>
array(3) {
[0]=>
string(13) "user_test_[4]"
[1]=>
string(12) "user_uat_[4]"
[2]=>
string(13) "user_prod_[4]"
}
}
I would say merge all array and then build the category array
$arrs = array_merge($array_usrtest, $array_usruat, $array_usrprod);
$categories = array_fill_keys($array_cat, []);
array_walk($arrs, function($item) use (& $categories){
preg_match('#(.*)\[(\d)\]#', $item, $matches);
$key = $matches[2];
$categories['Category' . $key][] = $item;
});
print_r($categories);
Based on yours answers:
<?php
$array_cat = array(1=>"Category1", 2=>"Category2", 3=>"Category3", 4=>"Category4");
$array_usrtest = array(1=>"user_test_[1]", 2=>"user_test_[2]", 3=>"user_test_[3]", 4=>"user_test_[4]");
$array_usruat = array(3=>"user_uat_[3]", 4=>"user_uat_[4]");
$array_usrprod = array(2=>"user_prod_[2]", 4=>"user_prod_[4]");
$values = array_merge($array_usrtest, $array_usruat, $array_usrprod);
$result = [];
foreach ($array_cat as $key => $cat) {
foreach ($values as $k => $value) { // iterate over all values
preg_match('!\d+!', $value, $match); // get index in [index]
if ($key == $match[0]) {
$result[$cat][] = $value; //append values to category
}
}
}
echo '<pre>';
var_dump($result);
?>
Result:
array(4) {
["Category1"]=>
array(1) {
[0]=>
string(13) "user_test_[1]"
}
["Category2"]=>
array(2) {
[0]=>
string(13) "user_test_[2]"
[1]=>
string(13) "user_prod_[2]"
}
["Category3"]=>
array(2) {
[0]=>
string(13) "user_test_[3]"
[1]=>
string(12) "user_uat_[3]"
}
["Category4"]=>
array(3) {
[0]=>
string(13) "user_test_[4]"
[1]=>
string(12) "user_uat_[4]"
[2]=>
string(13) "user_prod_[4]"
}
}
I have the following (nested) array:
array(3) { [16]=> array(3) { [0]=> int(159) [1]=> int(160) [2]=> int(158) }
[21]=> array(2) { [0]=> int(160) [1]=> int(158) }
[19]=> array(2) { [0]=> int(158) [1]=> int(159) } }
As you can see it contains 3 child array's. The child array's all contain the integer '158' as an value but also '159'. I want to somehow loop trough the child array's and do a check if all child array's contain that value. Then I want to return an array with only these values.
I know i could use array_intersect for this however the nested array's are generated dynamically so i'm not sure how to deal with this using array intersect:
<?php
$arr1 = array('158','250','342');
$arr2 = array('158','142','352');
$diff1 = array_intersect($arr1, $arr2);
print_r( $diff1 );
//RETURNS Array ( [0] => 158 )
?>
You can use the splat operator(...) to pass all the subarrays into array_intersect() in one go...
$arr1 = [['158','250','342'],['158','142','352'],['1421','158','3521']];
$diff1 = array_intersect(...$arr1);
print_r( $diff1 );
//RETURNS Array ( [0] => 158 )
After a bit searching around I found the following:
$result = call_user_func_array('array_intersect', $productStoreArray);
As seen on: php dynamic array_intersect
This solves my problem because it returns to me:
//RETURNS Array ( [0] => 158, 1 => 159 )