Convert Complex array to simple one (for CSV) - php

I want to convert my complex array to simpler one for exporting that converted simpler array to the CSV file.
Currently my array structure is like:
Array
(
[0] => Array
(
[_source] => Array
(
[block] => Array
(
[0] => Kurud
)
[district] => Array
(
[0] => Dhamtari
)
[state] => Array
(
[0] => Chhattisgarh
)
)
)
[1] => Array
(
[_source] => Array
(
[block] => Array
(
[0] => North-Bangeluru
)
[district] => Array
(
[0] => Bangalore
)
[state] => Array
(
[0] => Karnataka
)
)
)
)
and I want to convert above array to the below given format:
array(
array("block", "district", "state"),
array("Kurud","Dhamtari","Chhattisgarh"),
array("North-Bangeluru","Bangalore","Karnataka")
)
So keys will be the first element and then each element with his data.
This is what I tried:
foreach ($array as $key => $value) {
if (is_array($value)) {
$result = array_merge($result);
}
else {
$result[$key] = $value;
}
}
print_r(result);
thanks in advance...

How about:
$keys = array_keys($arr[0]["_source"]);
$res[] = $keys;
foreach($arr as $e) {
$temp = [];
foreach($keys as $k)
$temp[] = $e["_source"][$k][0];
$res[] = $temp;
}
Reference: array-keys
Live example: 3v4l

Related

PHP Loop through array with no index names

In PHP I have this structure of Array (some are empty, some not, some are multiple items):
Array
(
[0] => Array
(
)
[1] => Array
(
[0] => 16534
)
[2] => Array
(
)
[3] => Array
(
[0] => 16532
[1] => 16533
)
[4] => Array
(
)
[5] => Array
(
[0] => 14869
)
}
I want to loop through this array, so as the result I get only the numbers (all of them).
I tried it this way:
foreach ($myarray as $item) {
echo '<pre>' . print_r($item) . '</pre>';
// $result[] = $this->myMethod($item);
}
So in foreach I want to use all the items from array in my method.
However when I echo the $item in the loop, I have something like this:
Array ( )
Array ( [0] => 16534 )
Array ( )
Array ( [0] => 16532 [1] => 16533 )
Array ( )
Array ( [0] => 14869 )
So still arrays (also the empty ones), and not numbers.
Can you please help with this?
UPDATE: I just noticed, some of the arrays looks like this:
[6] => Array
(
[0] => Array
(
[id] => 269
[hours] => 21.0
)
)
[7] => Array
(
[0] => Array
(
[0] => Array
(
[id] => 2
[hours] => 12.0
)
[1] => Array
(
[id] => 7
[hours] => 24.0
)
)
[1] => Array
(
[0] => Array
(
[id] => 2
[hours] => 5.0
)
[1] => Array
(
[id] => 7
[hours] => 0.583
)
)
)
but here the solution works not.
This one seems working but it is now brutal foreach in foreach solution:
foreach ($myarray as $item2) {
foreach ($item2 as $key2 => $val2) {
if (isset($val2)) {
foreach ($val2 as $key4 => $val4) {
echo $val4['id'].',';
}
}
}
}
Just merge the array which will also remove the empties:
foreach(array_merge(...$myarray) as $item) {
// echo '<pre>' . print_r($item) . '</pre>';
$result[] = $this->myMethod($item);
}
This will also work and may be faster:
$result = array_map([$this, 'myMethod'], array_merge(...$myarray));
If you have an old PHP version you'll have to use array() instead of [] and:
call_user_func_array('array_merge', $myarray)
You are only looping through the main array.That's the reason why you are getting an array when you are printing the result set.(because those values are stored in sub arrays and you are not looping them.)
And to remove the sub arrays with empty values I'll use isset() so that you will get only the values.
Change your code into this.
foreach ($myarray as $item) {
foreach($item as $key=>$val){
if(isset($val){
$values[] = $val;
// $result[] = $this->myMethod($values);
}
}
}

How to make array key from array data value in associative array

I have a multidimensional associative array which has a set of array. I want to change my array index value from some array value.
I already tried some array functions but my array also contains some null array so laravel function keyBy not give me wanted result.
$arr1=array(0 =>array(),1=>array(0=>array('quan'=>10,'handle' => 'baroque'),1 =>array('quan'=>20,'handle' => 'baroque')),
2 =>array (0 =>array('quan' => 5,'handle' => 'adidas')));
My expected result array must be like this
$arr2=array(0 =>array(),'baroque'=>array(0=>array('quan'=>10,'handle' => 'baroque'),1 =>array('quan'=>20,'handle' => 'baroque')),
'adidas' =>array (0 =>array('quan' => 5,'handle' => 'adidas')));
You can use the classic foreach. Check if the handle on element 0 exists using isset, if it does, use that as the key.
$arr1 = //...
$result = array();
foreach($arr1 as $key => $val) {
if (is_array($val) && isset($val[0]["handle"])) $result[ $val[0]["handle"] ] = $val;
else $result[$key] = $val;
}
$result will be:
Array
(
[0] => Array
(
)
[baroque] => Array
(
[0] => Array
(
[quan] => 10
[handle] => baroque
)
[1] => Array
(
[quan] => 20
[handle] => baroque
)
)
[adidas] => Array
(
[0] => Array
(
[quan] => 5
[handle] => adidas
)
)
)
You can use without condition by grouping at the handle as key directly.
$result = [];
foreach ($arr as $key => $value) {
if (!empty($value)) {
foreach ($value as $key1 => $value1) {
$result[$value1['handle']][] = $value1;
}
} else {
$result[] = $value;
}
}
Demo
Output:-
Array
(
[0] => Array
(
)
[baroque] => Array
(
[0] => Array
(
[quan] => 10
[handle] => baroque
)
[1] => Array
(
[quan] => 20
[handle] => baroque
)
)
[adidas] => Array
(
[0] => Array
(
[quan] => 5
[handle] => adidas
)
)
)
Try this..
$res = [];
foreach($x as $key => $value)
{
if(empty($value))
{
$res[] = $value;
}
else
{
foreach($value as $v => $k)
{
if(array_key_exists($k['handle'],$res))
{
$res[$k['handle']][] = ['quan' => $k['quan'],'handle' => $k['handle']];
}
else
{
$res[$k['handle']][0] = ['quan' => $k['quan'],'handle' => $k['handle']];
}
}
}
}
The result is going to be like this.
Array
(
[0] => Array
(
)
[baroque] => Array
(
[0] => Array
(
[quan] => 10
[handle] => baroque
)
[1] => Array
(
[quan] => 20
[handle] => baroque
)
)
[adidas] => Array
(
[0] => Array
(
[quan] => 5
[handle] => adidas
)
)
)

Change value inside an array

I'd like to change the values of an array.
Currently my array looks like this:
Array
(
[0] => Array
(
[0] => 12-Multi_select-customfield-retina-ready+Yes
[1] => 12-Multi_select-customfield-retina-ready+N/A
[2] => 12-Multi_select-customfield-retina-ready+No
)
)
I want to remove everything before the + symbol, so in the end the new array will looke like this
Array
(
[0] => Array
(
[0] => Yes
[1] => N/A
[2] => No
)
)
This is my code:
$new_array = array();
foreach( $array as $key => $value ) {
$split = explode("+", $value[0]);
$new_array[] = $split[1];
}
Hoping that it would worked, but when I check the new array, it only shows one value.
Array
(
[0] => Yes
)
Any help in putting me in the right direction is much appreciated.
Please, check it:
<?php
$array[0][0] = '12-Multi_select-customfield-retina-ready+Yes';
$array[0][1] = '12-Multi_select-customfield-retina-ready+N/A';
$array[0][2] = '112-Multi_select-customfield-retina-ready+No';
echo '<pre>';
print_r($array);
$new_array = array();
foreach( $array[0] as $key => $value ) {
$split = explode("+", $value);
$new_array[] = $split[1];
}
print_r($new_array);
echo '</pre>';
Try This this work even if you have multiple key in the original array $original_array[0], $original_array[1] ... :
$original_array[0] = [
0 => '12-Multi_select-customfield-retina-ready+Yes',
1 => '12-Multi_select-customfield-retina-ready+N/A',
2 => '12-Multi_select-customfield-retina-ready+No'
];
print_r($original_array);
$new_array = [];
foreach ($original_array as $key => $value) {
foreach ($value as $index => $val) {
$split = explode("+", $val);
$new_array[$key][] = $split[1];
}
}
print_r($new_array);
Example :
Original array
Array
(
[0] => Array
(
[0] => 12-Multi_select-customfield-retina-ready+Yes
[1] => 12-Multi_select-customfield-retina-ready+N/A
[2] => 12-Multi_select-customfield-retina-ready+No
),
[1] => Array
(
[0] => 12-Multi_select-customfield-retina-ready+Yes
[1] => 12-Multi_select-customfield-retina-ready+N/A
[2] => 12-Multi_select-customfield-retina-ready+No
)
)
New Array
Array
(
[0] => Array
(
[0] => Yes
[1] => N/A
[2] => No
),
[1] => Array
(
[0] => Yes
[1] => N/A
[2] => No
)
)

php multidimensional array key value search from two different arrays

I have two different array. The array are like
first array is like
Array
(
[0] => Array
(
[source_language] => English
[target_language] => Array
(
[0] => German
[1] => Norwegian
)
[title] => file 1.xlsx
[file_name] => 1461911750_file_test.xlsx
)
[1] => Array
(
[source_language] => Hindi
[target_language] => Array
(
[0] => Belarusian
)
[title] => new files.xlsx
[file_name] => 1461912206_file_here_files.xlsx
)
)
Second array is like
Array
(
[1] => Array
(
[source_language] => English
[target_language] => Array
(
[0] => Urdu
[1] => Hindi
)
)
[2] => Array
(
[source_language] => Hindi
[target_language] => Array
(
[0] => Norwegian
)
)
[3] => Array
(
[source_language] => Hindi
[target_language] => Array
(
[0] => German
)
)
[3] => Array
(
[source_language] => English
[target_language] => Array
(
[0] => German
[1] => Norwegian
)
)
)
Now you can both array same key for source_langauge and target_language . The title and file_name key is available only in first array
So I want that the first array will search all the source_language and target_language from the second array and show both matching arrays and non matching arrays
So the output should be like this
The matching array is
[0] => Array
(
[source_language] => English
[target_language] => Array
(
[0] => German
[1] => Norwegian
)
[title] => file 1.xlsx
[file_name] => 1461911750_file_test.xlsx
)
as it has same values source language and target language in second array
The other result will show is
non matching array is
[0] => Array
(
[source_language] => Hindi
[target_language] => Array
(
[0] => Belarusian
)
[title] => new files.xlsx
[file_name] => 1461912206_file_here_files.xlsx
)
as this source language and target languages are not found in second array.
Update
I have tried so far is
$diffs = [];
foreach ($first_array as $a1) {
$h1 = md5(json_encode($a1));
$found = false;
foreach ($second_array as $a2) {
if (md5(json_encode($a2)) == $h1) {
$found = true;
break;
}
}
if ( !$found ) {
$diffs []= $a1;
}
}
But this one is not working at all
First off, you can't compare $h1 to $a2 since they don't share the exact same structure.
$h1 still has that title and filename key pair values.
No need to use md5 and json_encode, since you just need to compare two string values:
$match = $no_match = array();
foreach($first as $f) {
$found = false;
foreach($second as $s) {
if(
$f['source_language'] === $s['source_language'] &&
$f['target_language'] === $s['target_language']
) {
$match[] = $f;
$found = true;
}
}
if(!$found) {
$no_match[] = $f;
}
}
<?php
$arr1 = array();
$arr2 = array();
$arr1[0] = array('source_language'=>'English','target_language'=>array('German','Norwegian'),'title'=>'file 1.xlsx','file_name'=>'1461911750_file_test.xlsx');
$arr1[1] = array('source_language'=>'Hindi','target_language'=>array('Belarusian'),'title'=>'new files.xlsx','file_name'=>'1461912206_file_here_files.xlsx');
$arr2[0] = array('source_language'=>'English','target_language'=>array('Urdu','Hindi'));
$arr2[1] = array('source_language'=>'Hindi','target_language'=>array('Norwegian'));
$arr2[2] = array('source_language'=>'Hindi','target_language'=>array('German'));
$arr2[3] = array('source_language'=>'English','target_language'=>array('German','Norwegian'));
$result_arr = array();
for($i=0;$i<count($arr2);$i++)
{
for($j=0;$j<count($arr1);$j++)
{
if(($arr2[$i]['source_language'] === $arr1[$j]['source_language']) && ($arr2[$i]['target_language'] === $arr1[$j]['target_language']))
$result_arr[] = $arr1[$j];
}
}
print_r(json_encode($result_arr));
?>
The solution using array_walk and array_diff functions:
$matched = $not_matched = [];
array_walk($array1, function($v) use($array2, &$matched, &$not_matched){
foreach ($array2 as $item) {
if ($v['source_language'] == $item['source_language']
&& empty(array_diff($v['target_language'], $item['target_language']))) {
$matched[] = $v;
break;
}
}
if (!in_array($v, $matched)) $not_matched[] = $v;
});
echo "Matched items:". PHP_EOL;
print_r($matched);
echo "Not-matched items:". PHP_EOL;
print_r($not_matched);
The output:
Matched items:
Array
(
[0] => Array
(
[source_language] => English
[target_language] => Array
(
[0] => German
[1] => Norwegian
)
[title] => file 1.xlsx
[file_name] => 1461911750_file_test.xlsx
)
)
Not-matched items:
Array
(
[0] => Array
(
[source_language] => Hindi
[target_language] => Array
(
[0] => Belarusian
)
[title] => files.xlsx
[file_name] => 1461912206_file_here_files.xlsx
)
)

how to get array from get to normal array in php

I have an array like this and it can contain multiple values:
Array
(
[rpiid] => Array
(
[1] => 86
)
[sensor_id] => Array
(
[1] => 1
)
[when] => Array
(
[1] => 2014-02-24
)
[val] => Array
(
[1] => 000
)
[train] => Array
(
[1] => True
)
[valid] => Array
(
[1] => False
)
[button] => update
)
Of course, here there is only the number 1 each time but sometimes I have 0, 1, 2 and a value associated. This is because I get this from a GET from multiple forms.
How can I transform this array into
Array
(
[0] => Array
(
[rpiid] => 86
[sensor_id] => 1
...
Thanks,
John.
if your array is $get
$newArray = Array();
foreach($get as $secondKey => $innerArray){
foreach($value as $topKey => $value) {
$newArray[$topKey][$secondKey] = $value;
}
}
This should work
$new_array = array();
foreach($first_array as $value => $key){
$new_array[$key] = $value[1];
}
Sure you can, take a look at this small example:
$a = [ 'rpid' => [1], 'cpid' => [2,2] ];
$nodes = [];
foreach($a as $node => $array) {
foreach($array as $index => $value) {
if(empty($nodes[$index]))
$nodes[$index] = [];
$nodes[$index][$node] = $value;
}
}
print_r($nodes):
Array
(
[0] => Array
(
[rpid] => 1
[cpid] => 2
)
[1] => Array
(
[cpid] => 2
)
)

Categories