Transform array, set each array element with parent key php - php

I am receiving data that is an array of elements that contains an array of tags by language like this
[
{
"1": "tag_es1;tag_es2;tag_es3",
"2": "tag_en1;tag_en2;tag_en3"
},
{
"1": "tag_es1;tag_es2",
"2": "tag_en1;tag_en2"
}
]
I need to separate each tag by language, so i usearray_map to transform it like this
[
{
"1": [
"tag_es1",
"tag_es2",
"tag_es3"
],
"2": [
"tag_en1",
"tag_en2",
"tag_en3"
]
},
{
"1": [
"tag_es1",
"tag_es2"
],
"2": [
"tag_en1",
"tag_en2"
]
}
]
Bu what i need is the response to be like this
[
{
{
"1" : "tag_es1",
"2" : "tag_en1"
},
{
"1" : "tag_es2",
"2" : "tag_en2"
},
{
"1" : "tag_es3",
"2" : "tag_en3"
}
},
{
{
"1" : "tag_es4",
"2" : "tag_en4"
},
{
"1" : "tag_es5",
"2" : "tag_en5"
}
}
]
I tried using array_combine, array_walk, and manually doing it inside array_map, but with no success, what could i do?

Solution with special trick with null as callback of array_map:
$arr = json_decode($s, true);
$new_arr = [];
foreach ($arr as $item) {
$parts1 = explode(';', $item[1]);
$parts2 = explode(';', $item[2]);
// $new_arr[] = array_map(null, $parts1, $parts2);
$tmp_arr = array_map(null, $parts1, $parts2);
$new_arr[] = array_map(
function($v) { return array_combine(["1","2"], $v); },
$tmp_arr
);
}

You can loop the array and build a temporary array.
This array can then be looped and used array_column on to get the corresponding values to the new array.
$arr = json_decode($json, true);
foreach($arr as $key1 => $sub){
foreach($sub as $item){
$temp[] = explode(";", $item);
}
foreach($temp[0] as $key2 => $val){
$new[$key1][]= array_combine([1,2],array_column($temp, $key2));
}
$temp =[]; // empty array
}
var_dump($new);
Output:
array(2) {
[0]=>
array(3) {
[0]=>
array(2) {
[1]=>
string(7) "tag_es1"
[2]=>
string(7) "tag_en1"
}
[1]=>
array(2) {
[1]=>
string(7) "tag_es2"
[2]=>
string(7) "tag_en2"
}
[2]=>
array(2) {
[1]=>
string(7) "tag_es3"
[2]=>
string(7) "tag_en3"
}
}
[1]=>
array(2) {
[0]=>
array(2) {
[1]=>
string(7) "tag_es1"
[2]=>
string(7) "tag_en1"
}
[1]=>
array(2) {
[1]=>
string(7) "tag_es2"
[2]=>
string(7) "tag_en2"
}
}
}
https://3v4l.org/qgCA1
Added "1","2" as keys

The leanest, cleanest approach is three nested foreach loops.
Assign the dynamic keys when pushing data in the result array.
Code: (Demo)
$result = [];
foreach (json_decode($json, true) as $i => $row) {
foreach ($row as $id => $delimited) {
foreach (explode(';', $delimited) as $key => $value) {
$result[$i][$key][$id] = $value;
}
}
}
var_export($result);

Related

Convert PHP associative array to new array but only with specific keys?

I have data array on this way:
array(3) {
[0]=>
array(2) {
["name"]=>
string(13) "Register Page"
["id"]=>
string(1) "5"
}
[1]=>
array(2) {
["name"]=>
string(10) "Login Page"
["id"]=>
string(1) "6"
}
[2]=>
NULL
}
My goal is to get from the array above something like this:
array(5,6,null);
Thanks!
Look at the PHP function array_map
$array = [
["name" => "Register Page", "id" => 5 ],
["name" => "Login Page", "id" => 6 ],
NULL
];
$ids = array_map( function($rec) { return $rec['id'] ?? null; }, $array);
Assuming your data is in $a:
foreach ( $a as $a2 ) {
if ( is_array($a2) && $a2['id'] ) {
$r[] = $a2['id']; // or (int) $a2['id'] if you want to cast it to an int
} else {
$r[] = NULL;
}
}

Extract elements of certain type from an array in PHP

I have a multidimensional array I obtained from an Excel file (raw data from cells stripped of any formatting, styling info,etc.). Example of array:
array(1) {
[0]=>
array(4) {
[1]=>
array(1) {
["A"]=>
string(5) "aaaaa"
}
[2]=>
array(1) {
["A"]=>
NULL
}
[3]=>
array(1) {
["A"]=>
NULL
}
[4]=>
array(1) {
["A"]=>
float(666)
}
}
}
String-type cells represent ordinary text entered into a worksheet cells, while float-type cells represent numbers entered there.
Is there any method to extract the 'strings' and 'floats' from such an array? Or, can one at least delete all/filter out other info from an array by the type of its elements, leaving only 'string' and 'float' elements there?
Thank you!
Just check the array items recursively and remove the items which is not string, float or array with data.
Code example:
<?php
$data = [
[
['A' => 'aaaaa'],
['A' => null],
['A' => null],
['A' => (float)666]
]
];
function filterData($array)
{
foreach ($array as $key => &$value) {
if (is_array($value))
$value = filterData($value);
if ($value === [] || (!is_array($value) && !is_string($value) && !is_float($value)))
unset($array[$key]);
}
return $array;
}
var_dump(filterData($data));
/* result
array(1) {
[0]=>
array(2) {
[0]=>
array(1) {
["A"]=>
string(5) "aaaaa"
}
[3]=>
array(1) {
["A"]=>
float(666)
}
}
}
*/
As an alternative you might use a combination of array_map and array_filter and in the callback of array_filter check if the value is either a float or a string:
$arrays = [
[
['A' => 'aaaaa'],
['A' => null],
['A' => null],
['A' => (float)666]
]
];
$arrays = array_map(function($x) {
return array_filter($x, function($y) {
return is_float($y['A']) || is_string($y['A']);
});
}, $arrays);
var_dump($arrays);
Demo
That would result in:
array(1) {
[0]=>
array(2) {
[0]=>
array(1) {
["A"]=>
string(5) "aaaaa"
}
[3]=>
array(1) {
["A"]=>
float(666)
}
}
}

Php extract array value

I have an array structure like below.
//var_dump($data):
array(5) {
[0]=> string(1) "1"
[1]=> string(1) "2"
[2]=> string(4) "4=13"
[3]=> string(1) "4"
[4]=> string(3) "1=4"
}
Here value 1 and 4 has extension. So I need to get those values.
i.e Final output should be
$data = array(1,4);
$array = array("1", "2", "4=13", "4", "1=4");
$keys = array();
foreach ($array as $value) {
if (strpos($value, "=") !== false) {
list($key, $_) = explode("=", $value, 2);
$keys[] = (int) $key;
}
}
sort($keys);
var_dump($keys); // array(1, 4)

Count from two array php

I have two array, arrLevel1 and arrLevel2.
I want to count animal that can walk.
How can I do that array stucture like this?
Thx before. I already tried, but it failed.
arrLevel1:
array(4) {
[0]=>
array(1) {
["Walk"]=>
string(4) "Bird"
}
[1]=>
array(1) {
["Walk"]=>
string(3) "Cat"
}
[2]=>
array(1) {
["Fly"]=>
string(9) "ButterFLy"
}
[3]=>
array(1) {
["Fly"]=>
string(4) "Bird"
}
}
arrLevel2:
array(3) {
[0]=>
array(1) {
["Animal"]=>
string(3) "Fly"
}
[1]=>
array(1) {
["Animal"]=>
string(11) "Walk"
}
[2]=>
array(1) {
["Human"]=>
string(11) "Walk"
}
}
Just check them in a loop
For the first arrLevel1:
<?php
$arrLevel1 = array(array("walk"=>"Bird"),array("walk"=>"Cat"),array("Fly"=>"Butterfly"),array("Fly"=>"Bird"));
$x = 0;
foreach($arrLevel1 as $p){
if($p["walk"]!==null){
$x++;
}
}
var_dump($x);
?>
Hope thsi helps you
One way to do it is using array_reduce():
$array = array(array('Walk' => 'Bird'), array('Walk' => 'Cat'), array('Fly' => 'ButterFly'), array('Fly' => 'Bird'));
$count = array_reduce($array, function($carry, $item) {
return key($item) == 'Walk' ? $carry + 1 : $carry;
}, 0);
var_dump($count);
You can use a similar code for the second version:
$array = array(array('Animal' => 'Fly'), array('Animal' => 'Walk'), array('Human' => 'Walk'));
$count = array_reduce($array, function($carry, $item) {
return reset($item) == 'Walk' ? $carry + 1 : $carry;
}, 0);
var_dump($count);

Array values to check another array values in PHP?

I have an array $minus
array(3) { [0]=> string(6) "people"
[1]=> string(7) "friends"
[2]=> string(8) "siblings"
}
And I have an array $user
array(3) { ["people"]=> string(3) "100"
["friends"]=> string(2) "10"
["siblings"]=> string(2) "57"
}
I can get the values of $user by using the values of $minus like,
echo $user[$minus[0]] . ', ' . $user[$minus[1]] . ', ' . $user[$minus[2]];
// Would echo: 100, 10, 57
But how can I get the values of $user by using the values of $minus into a new array, the new array should be like,
array(3) { [0]=> string(3) "100"
[1]=> string(2) "10"
[2]=> string(2) "57"
}
I have tried using foreach loops but can never get it right?
foreach($minus as $key=>$value) {
$new_array[$key] = $user[$value];
}
Use array_map, PHP >= 5.3 only
$new_array = array_map(function($item) use ($user) {return $user[$item];}, $minus);
$new_array= array();
foreach ($minus as $key => $value){
$new_array[$key] = $user[$value];
}
print_r($new_array);
$new_array = array($user[$minus[0]], $user[$minus[1]], $user[$minus[2]]);
$minus = array(0 => "people",
1 => "friends",
2 => "siblings"
);
$user = array("people" => "100",
"friends" => "10",
"siblings" => "57"
);
$newArray = $minus;
array_walk($newArray,function(&$item, $key, $prefix) { $item = $prefix[$item]; },$user);
var_dump($newArray);

Categories