Store column data from a multidimensional array while preserving missing elements - php

I have an array ($myArray) which looks like
Array ( [0] =>
Array ( [0] =>
Array (
[Date] => 1776-08-08
[Color] => Yellow
[Description] => Rotten
) )
[1] => Array ( )
[2] =>
Array ([0] =>
Array (
[Date] => 2018-05-13
[Color] => Red
[Status] => Fresh
)
[1] =>
Array (
[Date] => 1991-03-29
[Color] => Green
[Status] => Fresh ) )
I loop though the content for the values of Date using
array_walk_recursive($myArray, function($v, $k){
if ($k == "Date") echo $v . PHP_EOL;
This would get me the correct output.
1776-08-08 2018-05-13 1991-03-29
I want to add the output into an array and even if the value is null (ie[1] above) to still set an empty array.
For example $newArray =
Array ( [0] => 1776-08-08 )
Array ( )
Array ( [0] => 2018-05-13 [1] => 1991-03-29 )

Given your example, an option is to use array_column() on each of the items in the outermost array, which is easy with the array_map() function.
$input = array(
array(
array(
"Date" => "1776-08-08",
"Color" => "Yellow",
"Description" => "Rotten",
),
),
array(
),
array(
array(
"Date" => "2018-05-13",
"Color" => "Red",
"Status" => "Fresh",
),
array(
"Date" => "1991-03-29",
"Color" => "Green",
"Status" => "Fresh",
),
),
);
$output = array_map(function($sub_arrays) {
return array_column($sub_arrays, "Date");
}, $input);
print_r($output);
The above will output something like:
Array
(
[0] => Array
(
[0] => 1776-08-08
)
[1] => Array
(
)
[2] => Array
(
[0] => 2018-05-13
[1] => 1991-03-29
)
)

You'll need to do a normal foreach loop for the top-level, and then use array_walk_recursive for the nested arrays.
$newArray = array();
foreach ($myArray as $el) {
$temp = array();
array_walk_recursive($el, function($v, $k) use (&$temp) {
if ($k == "Date") {
$temp[] = $v;
}
});
$newArray[] = $temp;
}
DEMO

Related

How to create arrays for each values - PHP

// ARRAY
(
[apple] => one
[orange] => two
[strawberry] => three
)
// NEW ARRAY
(
[0] => Array
(
[0] => apple
[1] => one
)
[1] => Array
(
[0] => orange
[1] => two
)
[2] => Array
(
[0] => strawberry
[1] => three
)
)
I want to create an array for each key of the current array, so i can use this in a foreach later. Is it possible?
I've tried everything without success.
You can loop through every elements in your associative array and create an empty array before the loop. Then push the key as well as value to the new array. This way you can get that desirable output:
<?php
$assocArray = [
"apple" => "one",
"orange" => "two",
"strawberry" => "three"
];
echo "Before: \n\r";
print_r($assocArray);
$newArray = [];
foreach ($assocArray as $key => $item) {
$newArray[] = [$key, $item];
}
echo "After: \n\r";
print_r($newArray);
Output
Before:
Array
(
[apple] => one
[orange] => two
[strawberry] => three
)
After:
Array
(
[0] => Array
(
[0] => apple
[1] => one
)
[1] => Array
(
[0] => orange
[1] => two
)
[2] => Array
(
[0] => strawberry
[1] => three
)
)
``
You can also do this:
$array = [
'apple' => 'one',
'orange' => 'two',
'strawberry' => 'three',
];
$output = array_map(function($k, $v) {
return [$k, $v];
}, array_keys($array), $array);
var_dump($output);

make inline result from array value

I have two array as bellow :
First array :
Array
(
[0] => Array
(
[0] => Array
(
[name] => one
[number] => 051
)
[1] => Array
(
[name] => two
[number] => 052
)
[2] => Array
(
[name] => three
[number] => 053
)
)
[1] => Array
(
[0] => Array
(
[name] => four
[number] => 061
)
[1] => Array
(
[name] => five
[number] => 062
)
)
)
I want to make output from first array above
[0] => 051, 052, 053.
[1] => 061, 062.
Array
(
[0] => Array
(
[0] => Array
(
[name] => book
[number] => 41
)
[1] => Array
(
[name] => pencil
[number] => 42
)
)
[1] => Array
(
[name] => eraser
[number] => 71
)
)
I want to make output from second array above
[0] => 41, 42.
[1] => 71.
Please advise. Thank you.
You can make a try like this way with two foreach() loop.
$numbers = [];
foreach ($array as $k => $v) {
$num = [];
foreach ($v as $k2 => $v2) {
$num[] = $v2['number'];
}
$numbers[$k] = implode(',',$num).'.';
}
print_r($numbers);
DEMO: https://3v4l.org/mEeO7
you can try something like this
$arr = Array (
Array (
Array (
"name" => "one",
"number" => "051"
),
Array (
"name" => "two",
"number" => "052"
),
Array (
"name" => "three",
"number" => "053"
)
),
Array (
Array (
"name" => "four",
"number" => "061"
),
Array (
"name" => "five",
"number" => "062"
)
)
);
foreach ($arr as $k => $s_arr) {
echo "[" . $k . "] => ";
foreach ($s_arr as $k2 => $v2) {
echo $v2["number"] . " ";
}
echo "\n";
}

Make associative array of unique values from column containing arrays

Array
(
[0] => Array
(
[id] => 21153
[genre] => ["History","Drama", "Thriller"]
)
[1] => Array
(
[id] => 21152
[genre] => ["ACTION"]
)
[2] => Array
(
[id] => 21151
[genre] => ["ROMANTIC"]
)
[3] => Array
(
[id] => 21150
[genre] => ["Drama"]
)
)
I have with the above array and I want to convert that array to an unique array as mentioned below, and there should be any duplicate values.
Array(
[History] => "History"
[ACTION] => "ACTION"
[ROMANTIC] => "ROMANTIC"
[Drama] => "Drama"
[Thriller]=>"Thriller"
)
I don't really get how the resulting array makes any sense, but here you are:
Loop through the array, loop through the genres and push items to a new array.
<?
$a = Array
(
[
"id" => 21153,
"genre" => ["History","Drama", "Thriller"]
],
[
"id" => 21152,
"genre" => ["ACTION"]
]
);
$result = [];
foreach($a as $b) {
foreach($b['genre'] as $genre) {
$result[$genre] = $genre; // don't need to check if it exists already, because we'll overwrite it anyway.
}
}
echo "<pre>";
print_r($result);
echo "</pre>";
// output:
Array
(
[History] => History
[Drama] => Drama
[Thriller] => Thriller
[ACTION] => ACTION
)
It can be done by using foreach() loop and in_array() function like below
$myArray=array();
$array = array(
array("id"=>21153,"genre"=>array("History","Drama", "Thriller")),
array("id"=>21152,"genre"=>array("ACTION")),
array("id"=>21151,"genre"=>array("ROMANTIC")),
array("id"=>21150,"genre"=>array("Drama"))
);
foreach($array as $arr){
foreach($arr as $genres){
if(is_array($genres)){
foreach($genres as $elem){
if (!in_array($elem, $myArray))
{
$myArray[$elem]=$elem;
}
}
}
}
}
print_r($myArray);
This is a function that resolves what you ask, though I'm not sure it is quite useful to have value and key being identical. I'm just looping over all genders and add only the ones I don't already have store in returning array. probably a bit dangerous with your code because it is case sensitive
function getGenders(array $rawValues) :array {
$distinctGenders = [];
foreach ($rawValues as $row) {
foreach ($row["genre"] as $gender) {
if (!in_array($gender, $distinctGenders)) {
$distinctGenders[$gender] = $gender;
}
}
}
return $distinctGenders;
}
By doing the changes, I have fixed this,
$responseData = Array(
[0] => Array
(
[id] => 21153
[genre] => ["History","Drama", "Thriller"]
)
[1] => Array
(
[id] => 21152
[genre] => ["ACTION"]
)
[2] => Array
(
[id] => 21151
[genre] => ["ROMANTIC"]
)
[3] => Array
(
[id] => 21150
[genre] => ["Drama"]
)
foreach ($responseData as $data){
$strReplace = str_replace(array('[',']') , '' , $data['genre']);
$explodeData[] = explode(',', $strReplace);
}
And the output after exploding is :
$explodeData = Array
(
[0] => Array
(
[0] => "History"
[1] => "Drama"
[2] => "Thriller"
)
[1] => Array
(
[0] => "ACTION"
)
[2] => Array
(
[0] => "ROMANTIC"
)
[3] => Array
(
[0] => "Drama"
)
)
And finally by the foreach loop :
foreach ($explodeData as $arr) {
foreach ($arr as $genres) {
if (!in_array($genres, $myArray)) {
$myArray[$genres] = $genres;
}
}
}
And finally the required output comes as below :
Array(
["History"] => "History"
["Drama"] => "Drama"
["Thriller"] => "Thriller"
["ACTION"] => "ACTION"
["ROMANTIC"] => "ROMANTIC"
)
Flatten the column of data.
Assign keys from the values (this ensures uniqueness).
Code: (Demo)
$array = [
["id" => 21153, "genre" => ["History", "Drama", "Thriller"]],
["id" => 21152, "genre" => ["ACTION"]],
["id" => 21151, "genre" => ["ROMANTIC"]],
["id" => 21150, "genre" => ["Drama"]]
];
$flat = array_merge(...array_column($array, 'genre'));
var_export(
array_combine($flat, $flat)
);
Output:
array (
'History' => 'History',
'Drama' => 'Drama',
'Thriller' => 'Thriller',
'ACTION' => 'ACTION',
'ROMANTIC' => 'ROMANTIC',
)

Array inside array or nested array

I have an array like below: all the values I am getting one array only, but I don't want this way. This is the best way to do so, in php or jQuery both languages are ok for me
Array
(
[0] => Array
(
[val] => facebook
)
[1] => Array
(
[val] => snapchat
)
[2] => Array
(
[val] => instagram
)
[3] => Array
(
[expenses] => 986532
)
[4] => Array
(
[expenses] => 45456
)
[5] => Array
(
[expenses] => 56230
)
[6] => Array
(
[social_id] => 15
)
[7] => Array
(
[social_id] => 16
)
[8] => Array
(
[social_id] => 17
)
)
and I want to output like this..
$result = array(
array(
"val" => "Facebook",
"expenses" => "84512",
"social_id" => 1
),
array(
"val" => "Instagram",
"expenses" => "123",
"social_id" => 2
)
);
but this should be dynamic, the length of the above array can be varies
You can merge the arrays to one and use array_column to get all vals or expenses in a separate array.
Then foreach one array and build the new array with the key.
//$a = your array
// Grab each column separate
$val = array_column($a, "val");
$expenses= array_column($a, "expenses");
$social_id = array_column($a, "social_id");
Foreach($val as $key => $v){
$arr[] = [$v, $expenses[$key], $social_id[$key]];
}
Var_dump($arr);
https://3v4l.org/nVtDf
Edit updated with the 'latest' version of the array. My code works just fine with this array to without any changes.
to get that array style you can do it by hand for each array
function test(array ...$arr)
{
$result = array();
foreach ($arr as $key => $pair) {
foreach ($pair as $item => $value) {
$result[$item] = $value;
}
}
return $result;
}
$arr1 = test( ['facebook' => 1], ['expenses' => 100]);
print_r($arr1);
/* Array (
[facebook] => 1,
[expenses] => 100
)
*/
$arr2 = test( $arr1, ['more info' => 'info'] );
print_r($arr2);
/* Array (
[facebook] => 1,
[expenses] => 100,
[more info] => info
)
*/
you can pass it any number of
['Key' => 'Pair']
array('Key' => 'Pair')
or even a previous made array and it will add them up into 1 big array and return it

merging mutidimensional arrays

I have an array that looks like this:
getting array need to convert array as same key value as 0
foreach($array as $key=>$id){
$consumer_data[]=$this->App_model->get_session($id);
}
print_r($consumer_data);
Array
(
[0] => Array
(
[0] => Array
(
[ConsumerID] => 1
[name] => asdfd
)
[1] => Array
(
[ConsumerID] => 5
[name] => test
)
[2] => Array
(
[ConsumerID] => 3
[name] => test1
)
)
[1] => Array
(
[0] => Array
(
[ConsumerID] => 4
[name] => test4
)
)
i want to implement array like this in same key value as 0
Array
(
[0] => Array
(
[0] => Array
(
[ConsumerID] => 1
[name] => asdfd
)
[1] => Array
(
[ConsumerID] => 5
[name] => test
)
[2] => Array
(
[ConsumerID] => 3
[name] => test1
)
[3] => Array
(
[ConsumerID] => 4
[name] => test4
)
)
I am using PHP. Can anyone point me to a good starting point as to how I should go about doing this?
You can use array_merge():
$new_array[0] = array_merge($array[0], $array[1]);
Where $array is the first array.
SEE DEMO
OR for a more dynamic approach:
$new_array = array(0 => array());
foreach($array as $a) {
$new_array[0] = array_merge($new_array[0], $a);
}
SEE DEMO 2
The simpliest solution is to do it with:
$input = array(
array(
array('ConsumerID' => 1, 'name' => 'asdfd'),
array('ConsumerID' => 5, 'name' => 'test'),
array('ConsumerID' => 4, 'name' => 'test1'),
),
array(
array('ConsumerID' => 4, 'name' => 'test4'),
),
);
$output = array(
array()
);
foreach ($input as $data) {
$output[0] = array_merge($output[0], $data);
}
Try this->
$newArray = array();
foreach($values as $key=>$val){
$newArray [0][$key]=$val;
}
print_r($newArray);
Check this:
<?php
$arr[0] = array(0 => array("ConsumerID" => 1, "name" => "Ni"), 1 => array("ConsumerID" => 2, "name" => "Ab"));
$arr[1] = array(1 => array("ConsumerID" =>5, "name" => "GE"), 1 => array("ConsumerID" => 6, "name" => "DB"));
$new = array();
foreach($arr as $key => $value) {
foreach($value as $innerkey => $innervalue) {
$new[0][] = $innervalue;
}
}
print_r($new);
?>

Categories