PHP array_keys multiple levels - php

I have array1 like this:
Array
(
[0] => 123
[1] => 456
[2] => 789
)
And array 2 like this
Array
(
[0] => Array
(
[0] => some text
[1] => 888
[2] => some
[3] => text
)
[1] => Array
(
[0] => some text
[1] => 123
[2] => some
[3] => text
)
[2] => Array
(
[0] => some text
[1] => 999
[2] => some
[3] => text
)
[3] => Array
(
[0] => some text
[1] => Array
(
[1] => 456
[2] => 789
)
[2] => some
[3] => text
)
[4] => Array
(
[0] => some text
[1] => 123
[2] => some
[3] => text
)
)
I am checking only 1. column of second array and finding values that match values from first array. This is my code:
$test=array();
$xcol = array_column($array2, 1);
foreach( $array1 as $key => $value ) {
if( ($foundKey = array_keys($xcol, $value)) !== false ) {
$rrt=$foundKey;
foreach($rrt as $rte){
$test[]=$array2[$rte];
}
}
}
echo "<pre>";
print_r($test);
echo "</pre>";
It is working and giving me proper results but it does not check for all levels. Can anybody please point me what am I doing wrong?
My output is:
Array
(
[0] => Array
(
[0] => some text
[1] => 123
[2] => some
[3] => text
)
[1] => Array
(
[0] => some text
[1] => 123
[2] => some
[3] => text
)
)
And desired output is:
Array
(
[0] => Array
(
[0] => some text
[1] => 123
[2] => some
[3] => text
)
[1] => Array
(
[0] => some text
[1] => Array
(
[1] => 456
[2] => 789
)
[2] => some
[3] => text
)
[2] => Array
(
[0] => some text
[1] => 123
[2] => some
[3] => text
)
)

Solution:
create a loop which loop your $array2 which holds datas you wanted to get whos values match in first array $array1
foreach($array2 as $data) {
Inside loop create another loop which loop your indexes
foreach($data as $value) {
But before than create a condition if your index value is array loop it and check it it's index value is match in any indexes from $array1 use php function in_array for that
if (gettype($value) == "array") {
foreach($value as $val) {
if (in_array($val, $array1) ) {
$result[] = $data;
Then if you find it just stop the loop using break to avoid duplication
break;
}
}
Else you just directly use in_array
} else if (in_array($value, $array1)) {
$result[] = $data;
}
}
}
Just grab the code here in Demo
Help it helps just mark it answer if you are satisfied to it

Lets make a recursive method for this. What is recursion you ask? Well it is simply a method that calls it self.
<?php
$array1 = array(123,456,789);
$array2 = array(
array(
"some text"
, 888
, "some"
, "text"
),
array(
"some text"
,123
,"some"
,"text"
),
array(
"some text"
,999
,"some"
,"text"
),
array(
"some text"
,array(456,789)
,"some"
,"text"
),
array(
"another text"
,123
,"some"
,"text"
)
);
$final = array();
foreach($array1 as $needle){
foreach($array2 as $haystack){
if(find($needle,$haystack)){
$final[] = $haystack;
}
}
}
print_r($final);
function find($needle, $haystack){
$result = false;
foreach ($haystack as $value) {
if(is_array($value)){
$result = find($needle, $value);
} else {
if($needle == $value){
$result = true;
}
}
}
return $result;
}

Related

Reading text file into an array

I am looking to convert a text based DAT file into an array in PHP. Normally I would be able to read each line and explode it into an array but this file is different.
[0]
FirstRideOn=43169.5701090972
Laps=4591
LastRideOn=43224.7924173611
Name=Standard 1
Nr=1
ResetDate=0
RunningTime=2481
Runs=233
TranNr=7435191
[1]
FirstRideOn=43149.5406271644
Laps=5528
LastRideOn=43224.7616565972
Name=Standard 2
Nr=2
ResetDate=0
RunningTime=2957
Runs=292
TranNr=8377256
I was hoping to load it into an associative array.
Any feedback or suggestions are greatly appreciated!
It's not clear from your question exactly what format you want the array to be in. So here are two alternatives. First we read the file into an array:
$input= file('somefile.dat', FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
Then we can process the array to make an associative array. Here's the first option:
$output = array();
foreach ($input as $line) {
if (preg_match('/^\[(\d+)\]$/', $line, $matches)) {
$entry = (int)$matches[1];
$output[$entry] = array();
}
else {
list($key, $value) = explode('=', $line);
$output[$entry][$key] = $value;
}
}
print_r($output);
Which generates this output:
Array
(
[0] => Array
(
[FirstRideOn] => 43169.5701090972
[Laps] => 4591
[LastRideOn] => 43224.7924173611
[Name] => Standard 1
[Nr] => 1
[ResetDate] => 0
[RunningTime] => 2481
[Runs] => 233
[TranNr] => 7435191
)
[1] => Array
(
[FirstRideOn] => 43149.5406271644
[Laps] => 5528
[LastRideOn] => 43224.7616565972
[Name] => Standard 2
[Nr] => 2
[ResetDate] => 0
[RunningTime] => 2957
[Runs] => 292
[TranNr] => 8377256
)
)
Or we can do it this way:
// alternate style
$output = array();
foreach ($input as $line) {
if (preg_match('/^\[(\d+)\]$/', $line, $matches)) {
$entry = (int)$matches[1];
}
else {
list($key, $value) = explode('=', $line);
if (!array_key_exists($key, $output)) $output[$key] = array();
$output[$key][$entry] = $value;
}
}
print_r($output);
which generates this output. The choice is yours!
Array
(
[FirstRideOn] => Array
(
[0] => 43169.5701090972
[1] => 43149.5406271644
)
[Laps] => Array
(
[0] => 4591
[1] => 5528
)
[LastRideOn] => Array
(
[0] => 43224.7924173611
[1] => 43224.7616565972
)
[Name] => Array
(
[0] => Standard 1
[1] => Standard 2
)
[Nr] => Array
(
[0] => 1
[1] => 2
)
[ResetDate] => Array
(
[0] => 0
[1] => 0
)
[RunningTime] => Array
(
[0] => 2481
[1] => 2957
)
[Runs] => Array
(
[0] => 233
[1] => 292
)
[TranNr] => Array
(
[0] => 7435191
[1] => 8377256
)
)

PHP: Modify array's elements sequence

I've an php array that I've got from Excel file, for example:
$arrayOne
Array
{
[0] => Array
{
[0] => 0_age
[1] => 1_academic id
[2] => 2_name
[3] => 3_sex
}
[1] => Array
{
[0] => 0_18
[1] => 1_110291
[2] => 2_Jason
[3] => 3_Male
}
}
and in the mid of proccess, the array value from index [0] that consist data from Excel Header set into duallistbox for elimination and sorting then set into new array $newArray. So then, I got this array result:
$newArray
Array
{
[0] => Array
{
[0] => 2_name
[1] => 1_academic id
[2] => 3_sex
}
}
And I expect the system also can eliminate and sorting the data of array from index [1] that consist of Excel Data.
So the expected result is like this:
$expectedArray
Array
{
[0] => Array
{
[0] => 2_Jason
[1] => 1_110291
[2] => 3_Male
}
}
anyone know idea or how to solve this case? I've add an id(e.g: 0_) in each of array value that maybe useful for sorting.
Thanks
Edited
The sorting is based on the id that have been set on each value of array, so each element on array index [1] from $arrayOne is reset into new sequence adapted to same id from $newArray.
One way
<?php
$arr = array(
array
(
"0_age",
"1_academic id",
"2_name",
"3_sex",
),
array
(
"0_18",
"1_110291",
"2_Jason",
"3_Male",
),
array
(
"0_28",
"1_110291111",
"2_Jason Second",
"3_Female",
)
);
?>
<pre>
<?php
$new_array = array();
$count = 0;
foreach($arr as $a){
if($count==0){
}else{
$new_array[] = array(
$arr[0][0] => $a[0],
$arr[0][1] => $a[1],
$arr[0][2] => $a[2],
$arr[0][3] => $a[3],
);
}
$count=$count+1;
}
print_r($new_array);
?>
</pre>
Output
Array
(
[0] => Array
(
[0_age] => 0_18
[1_academic id] => 1_110291
[2_name] => 2_Jason
[3_sex] => 3_Male
)
[1] => Array
(
[0_age] => 0_28
[1_academic id] => 1_110291111
[2_name] => 2_Jason Second
[3_sex] => 3_Female
)
)
Second Way that exactly match with your output
$new_array = array();
$count = 0;
foreach($arr as $a){
if($count==0){
}else{
$new_array[] = array(
//$a[0],
$a[2],
$a[1],
$a[3],
);
}
$count=$count+1;
}
print_r($new_array);
Output:
Array
(
[0] => Array
(
[0] => 0_18
[1] => 1_110291
[2] => 2_Jason
[3] => 3_Male
)
[1] => Array
(
[0] => 0_28
[1] => 1_110291111
[2] => 2_Jason Second
[3] => 3_Female
)
)
You can search, Sort and remove any field. Update on the basis of your requirement.

How to parse this simple text-block into a multi-dimensional array, in PHP?

I have a simple text-block; and, its content is:
txt_1(val_1,val_2,val_3).
txt_1(val_4,val_5,val_6).
txt_2(val_7,val_8,val_9).
txt_3(val_10,val_11,val_12).
txt_3(val_13,val_14,val_15).
txt_4(val_16,val_17,val_18).
And, there is already an simple array, in PHP code:
$my_array = array();
Now, I want to parse into this PHP array, like:
Array
(
[txt_1] => Array
(
[0] => Array
(
[0] => val_1
[1] => val_2
[2] => val_3
)
[1] => Array
(
[0] => val_4
[1] => val_5
[2] => val_6
)
)
[txt_2] => Array
(
[0] => Array
(
[0] => val_7
[1] => val_8
[2] => val_9
)
)
[txt_3] => Array
(
[0] => Array
(
[0] => val_10
[1] => val_11
[2] => val_12
)
[1] => Array
(
[0] => val_13
[1] => val_14
[2] => val_15
)
)
[txt_4] => Array
(
[0] => Array
(
[0] => val_16
[1] => val_17
[2] => val_18
)
)
)
All data is general. Could you help me to do it, with PHP?
<?php
// Initially put your input into a variable
$txt=<<<__EOT__
txt_1(val_1,val_2,val_3).
txt_2(val_4,val_5,val_6).
txt_n(val_a,val_b,val_c).
__EOT__;
$result = array();
// separate out each row
$rows = explode("\n", $txt);
// loop through each row
foreach($rows as $row) {
// Use a regular expression to find the key and values
$success = preg_match('/^([^(]+)\(([^)]+)\)\.$/', $row, $parts);
// Check the regexp worked
if(!$success) {
echo 'Failed to match row: ' . $row . "\n";
continue;
}
// get the array key from the regexp results
$key = $parts[1];
// the values are all a string, split on the comma to make an array
$values = explode(',', $parts[2]);
// store $key and $values in the result
$result[$key] = $values;
}
// See if it worked
var_dump($result);
Suppose this answer will help you
$text = "
txt_1(val_1,val_2,val_3).
txt_2(val_4,val_5,val_6).
txt_3(val_a,val_b,val_c).
";
$myArry = explode(".", $text);
$resArry = array();
foreach ($myArry as $key => $value) {
if(trim($value)!=""){
$plain = str_replace(array("(",")"),",",$value);
$subArry = explode(",",$plain);
$keyN = explode("(",trim($value));
unset($subArry[array_search($keyN[0],$subArry)]);
unset($subArry[array_search("",$subArry)]);
$resArry[$keyN[0]][]=$subArry;
}
}
echo "<pre/>";
print_r($resArry);
die;
//Output will be like
Array
(
[txt_1] => Array
(
[0] => Array
(
[1] => val_1
[2] => val_2
[3] => val_3
)
)
[txt_2] => Array
(
[0] => Array
(
[1] => val_4
[2] => val_5
[3] => val_6
)
)
[txt_3] => Array
(
[0] => Array
(
[1] => val_a
[2] => val_b
[3] => val_c
)
)
)
$input = 'txt_1(val_1,val_2,val_3).
txt_1(val_4,val_5,val_6).
txt_2(val_7,val_8,val_9).
txt_3(val_10,val_11,val_12).
txt_3(val_13,val_14,val_15).
txt_4(val_16,val_17,val_18).'; // the input string
$temp = explode('.', $input); // seprates from .
$temp = array_filter($temp); // for cutting blank values
$temp = array_map('trim', $temp); // removes newlines
$final = [];
foreach($temp as $val)
{
$key = strtok($val, '('); // search upto token (
$final[$key][] = explode(',' ,strtok(')')); // advance token to )
}
unset($val, $temp); // unset non required things
Here is the output for $final,
Array
(
[txt_1] => Array
(
[0] => Array
(
[0] => val_1
[1] => val_2
[2] => val_3
)
[1] => Array
(
[0] => val_4
[1] => val_5
[2] => val_6
)
)
[txt_2] => Array
(
[0] => Array
(
[0] => val_7
[1] => val_8
[2] => val_9
)
)
[txt_3] => Array
(
[0] => Array
(
[0] => val_10
[1] => val_11
[2] => val_12
)
[1] => Array
(
[0] => val_13
[1] => val_14
[2] => val_15
)
)
[txt_4] => Array
(
[0] => Array
(
[0] => val_16
[1] => val_17
[2] => val_18
)
)
)
Test it here: http://phptester.net/
NOTE: In order to use the short array syntax [] use PHP 5.4
<?php
$text = "
txt_1(val_1,val_2,val_3).
txt_2(val_4,val_5,val_6).
txt_n(val_a,val_b,val_c).
";
$myArray = [];
//You're gonna see why we want to remove this character
//later, it will help us have a cleaner code.
$text = str_replace(')', '', $text);
$arrayGroup = explode('.', $text);
//print_r($arrayGroup);
foreach($arrayGroup as $array) {
$exp = explode('(', $array);
$arrayName = trim($exp[0]);
$arrayValues = explode(',', $exp[1]);
foreach($arrayValues as $value) {
${$arrayName}[] = $value;
}
$myArray[$arrayName] = $$arrayName;
}
echo '<pre>';
print_r($myArray);
echo '</pre>';
echo '<pre>';
print_r($myArray['txt_2']);
echo '</pre>';
After all this, you can use the txt_1 or txt_2 or whatever later, because the variables were created dynamically.
Later in the code you can use $myVar = txt_1[3]; with no problem

How to merge multidimensional arrays where only subarrays are affected? [duplicate]

This question already has answers here:
Merge row data from multiple arrays
(6 answers)
Closed 5 months ago.
here: Transforming array values in elements of a subarray using PHP I asked quite the same, but the arrays were flatter. I tried to adapt the code, but unfortunately without success.
How could I merge following arrays so the second array won't be added after the end of the first array, but each subarray of the first array will receive the correspondent values of subarrays of the second. In other words, I want to merge the subarrays. Here my example:
Array 01:
Array01 (
[0] => Array
(
[0] => 40292633
[1] => 412
)
[1] => Array
(
[0] => 41785603
[1] => 382
)
[2] => Array
(
[0] => 48792980
[1] => 373
)
[3] => Array
(
[0] => 44741143
[1] => 329
))
Array 02:
Array02(
[0] => Array
(
[0] => 3460581
[1] => 1407424B1
[2] => 951753
)
[1] => Array
(
[0] => 3484251
[1] => 1028325B1
[2] => 159357
)
[2] => Array
(
[0] => 3519102
[1] => 0586365A1
[2] => 456654
)
[3] => Array
(
[0] => 3529714
[1] => 1059876A1
[2] => 852258
))
Final array:
finalArray(
[0] => Array
(
[0] => 40292633
[1] => 412
[2] => 3460581
[3] => 1407424B1
[4] => 951753
)
[1] => Array
(
[0] => 41785603
[1] => 382
[2] => 3484251
[3] => 1028325B1
[4] => 159357
)
[2] => Array
(
[0] => 48792980
[1] => 373
[2] => 3519102
[3] => 0586365A1
[4] => 456654
)
[3] => Array
(
[0] => 44741143
[1] => 329
[2] => 3529714
[3] => 1059876A1
[4] => 852258
))
Many thanks in advance!
try this code
function merge_arrays($a1, $a2) {
return array($a1, $a2);
}
$result = array_map("merge_arrays", $a1, $a2);
foreach($result as $nr)
{
$nres[] = array_merge ($nr[0], $nr[1]);
}
Try this:
$result = array();
$keys = array_unique( array_merge(array_keys($arr1), array_keys($arr2)) );
foreach($keys as $key) {
if( !array_key_exists($key, $arr1) ) {
$result[$key] = $arr2;
} else if( !array_key_exists($key, $arr2) ) {
$result[$key] = $arr1;
} else {
$result[$key] = array_merge($arr1[$key], $arr2[$key]);
}
}
It does not assume that both arrays have the same keys.
If you'd like to use array_map, this is an equivalent solution:
$keys = array_unique( array_merge(array_keys($arr1), array_keys($arr2)) );
$result = array_map(function($key) use ($arr1,$arr2) {
if( !array_key_exists($key, $arr1) ) {
return $arr2;
} else if( !array_key_exists($key, $arr2) ) {
return $arr1;
}
return array_merge($arr1[$key], $arr2[$key]);
},
$keys);
If you're sure both arrays have the same keys, you can try this:
$result = array();
foreach($arr1 as $key => $arr1val) {
$result[$key] = array_merge($arr1val, $arr2[$key]);
}

Create a multidimensional array in PHP by separating each line based off a specific value

This is the array I have:
Array
(
[0] => name:string:255
[1] => weight:integer
[2] => description:string:255
[3] => age:integer
)
I want it to look like this
NewArray
(
[0] => Array
(
[0] => name
[1] => string
[2] => 255
[1] => Array
(
[0] => weight
[1] => integer
[2] => Array
(
[0] => description
[1] => string
[2] => 255
[3] => Array
(
[0] => age
[1] => integer
)
Or better yet, I would prefer this result. Making two separate arrays based off the number of groups.
NewArray1
(
[0] => Array
(
[0] => name
[1] => string
[2] => 255
[1] => Array
(
[0] => description
[1] => string
[2] => 255
)
NewArray2
(
[0] => Array
(
[0] => weight
[1] => integer
[1] => Array
(
[0] => age
[1] => integer
)
I have tried exploding and implode and foreaching but I'm not quite getting the result I want.
Use array_reduce() to build a new array while iterating over the old, splitting it up by type:
$array = [
'name:string:255',
'weight:integer',
'description:string:255',
'age:integer',
];
$result = array_reduce($array, function(&$result, $item) {
$parts = explode(':', $item, 3);
$result[$parts[1]][] = $parts;
return $result;
}, []);
Try this:
<?php
$array = array("name:string:255", "weight:integer", "description:string:255", "age:integer");
function map_func($value) {
return explode(':', $value);
}
$newArray = array_map(map_func, $array);
echo "Output 1:\n";
print_r($newArray);
$sorted = array();
foreach($newArray as $el)
$sorted[$el[1]][] = $el;
echo "Output 2:\n";
print_r($sorted);
Output:
Output 1:
Array
(
[0] => Array
(
[0] => name
[1] => string
[2] => 255
)
[1] => Array
(
[0] => weight
[1] => integer
)
[2] => Array
(
[0] => description
[1] => string
[2] => 255
)
[3] => Array
(
[0] => age
[1] => integer
)
)
Output 2:
Array
(
[string] => Array
(
[0] => Array
(
[0] => name
[1] => string
[2] => 255
)
[1] => Array
(
[0] => description
[1] => string
[2] => 255
)
)
[integer] => Array
(
[0] => Array
(
[0] => weight
[1] => integer
)
[1] => Array
(
[0] => age
[1] => integer
)
)
)
I doubt the following is the best solution but it does return what you wanted.
$array = array(
"0" => "name:string:255",
"1" => "weight:integer",
"2" => "description:string:255",
"3" => "age:integer"
);
foreach ($array as $key => $val) {
foreach (explode(':', $val) as $part) {
$new_array[$key][] = $part;
}
}
print_r($new_array);
above returns the following.
Array
(
[0] => Array
(
[0] => name
[1] => string
[2] => 255
)
[1] => Array
(
[0] => weight
[1] => integer
)
[2] => Array
(
[0] => description
[1] => string
[2] => 255
)
[3] => Array
(
[0] => age
[1] => integer
)
)
So you have a 1-dimentional array of strings ($arr01) . strings are separated by :
and you need to have a 2-dimentional array ($arr02) where the second dimension is an array of strings composed by splitting the initial set of strings based on their separator character :
$arr01 = array("name:string:255", "weight:integer", "description:string:255", "age:integer");
$arr02 = array(array());
for($i=0; $i<sizeof($arr01); $i++) {
$arr02[$i] = explode(":",$arr01[$i]);
}
display the two arrays....
echo "array 01: <br>";
for($i=0; $i<sizeof($arr01); $i++) {
echo "[".$i."] ".$arr01[$i]."<br>";
}
echo "<br><br>";
echo "array 02: <br>";
for($i=0; $i<sizeof($arr01); $i++) {
echo "[".$i."] ==> <br>";
for($j=0; $j<sizeof($arr02[$i]); $j++) {
echo " [".$j."] ".$arr02[$i][$j]." <br>";
}
}
echo "<br><br>";

Categories