I'm banging my head against what I am sure is a simple fix to re-structure an array. I don't have any choice over how the array is given to me:
Array
(
[author] => Array
(
[0] => John Doe
)
[journal] => Array
(
[0] => Biology
)
)
But I need the following:
Array
(
[author] => John Doe
[journal] => Biology
)
I've been working on various routes, but my brain doesn't work like this right now...
$result = [];
foreach ($data as $key => $value) {
$result[$key] = $value[0];
}
var_dump($result);
<?php
function reduce_array($array) {
$new = array();
foreach($array as $key => $value) {
$new[$key] = $value[0];
}
return $new;
}
?>
Related
In a foreach loop i would like to compare [name] value beetween different arrays but they have not the same levels.
Array(
[array1] => Array
(
[0] => WP_Term Object
(
[name] => Plafond
)
)
[array2] => WP_Term Object
(
[name] => Chaudière
)
[array3] => Array
(
[0] => WP_Term Object
(
[name] => Pla
)
[1] => WP_Term Object
(
[name] => Toc
)
)
)
I don't know how could i get the [name] in the same loop whereas levels are different.
I have tried to make :
foreach( $fields as $name => $value )
{
echo $value->name; }
Should i add another loop in the first loop ?
thanks
So your data looks like this:
$json = '{"array1":[{"name":"Plafond"}],"array2":{"name":"Chaudière"},"array3":[{"name":"Pla"},{"name":"Toc"}]}';
$array = json_decode($json);
If you don't know how deep it will go, a simple recursive function should work. Perhaps something like this:
function get_name($o, &$output) {
if (is_array($o)) {
foreach($o as $v) {
get_name($v, $output);
}
} elseif (property_exists($o, "name")) {
$output[] = $o->name;
}
}
$output = [];
foreach ($array as $v) {
get_name($v, $output);
}
If you data is going to look like the sample you provided (i.e. it will always be first or second level) then you don't need to worry about recursion.
$output = [];
foreach ($array as $k=>$v) {
if (is_array($v)) {
foreach ($v as $k2=>$v2) {
$output[] = $v2->name;
}
} else {
$output[] = $v->name;
}
}
Either way, your output values are all in the $output array:
print_r($output);
Output:
Array
(
[0] => Plafond
[1] => Chaudière
[2] => Pla
[3] => Toc
)
You can use array_map, array_key_exists to retrive the name index from the array
$jsonFormat = '{"array1":[{"name":"Plafond"}],"array2":{"name":"Chaudière"},"array3":[{"name":"Pla"},{"name":"Toc"}]}';
$jsonArray = json_decode($jsonFormat,true);
$res = [];
array_map(function($v) use (&$res){
if(array_key_exists('name', $v)){
$res[] = $v['name'];
}else{
foreach($v as $_key => $_value){
$res[] = $_value['name'];
}
}
}, $jsonArray);
echo '<pre>';
print_r($res);
Result:-
Array
(
[0] => Plafond
[1] => Chaudière
[2] => Pla
[3] => Toc
)
You can use $res to compare the names.
Array
(
[data] => Array
(
[0] => Array
(
['degree_level'] => Bachelor's
)
[1] => Array
(
['field_of_study'] => Science
)
[2] => Array
(
['grade_point'] => 3
)
[3] => Array
(
['criteria'] => desired
)
)
)
What I want :
Array
(
[data] => Array
(
['degree_level'] => Bachelor's
['field_of_study'] => Science
['grade_point'] => 3
['criteria'] => desired
)
)
You should use array_flatten(); to achieve your goal like this,
$flattened = array_flatten(Your_Data_Array);
Please give it a try and let me know.
UPDATE
$flattened = array_map(function($item) {
return $item[0];
}, Your_Data_Array);
For more information you can visit this for PHP functions.
Let me know in case of any queries.
$output = array_map(function($item) { return $item[0]; }, $myArray);
Try this,
foreach($data as $key1=>$val1){
foreach($val1 as $key2=>$val2){
$new_array[$key2] = $val2;
}
}
You can do it by loop.
foreach ($data as $key => $value) {
foreach ($value as $key1 => $value2) {
$data[$key1] = $value2;
}
}
You could use for example a double foreach loop to use the key and the value from the second loop and add those to the $arrays["data"] array.
Then you could use unset to remove the nested arrays.
$arrays = [
"data" => [
["degree_level" => " Bachelor's"],
["field_of_study" => "Science"],
["grade_point" => 3],
["criteria" => "desired"]
]
];
foreach($arrays["data"] as $dataKey => $data) {
foreach ($data as $key => $value) {
$arrays["data"][$key] = $value;
}
unset($arrays["data"][$dataKey]);
}
print_r($arrays);
That would give you:
Array
(
[data] => Array
(
[degree_level] => Bachelor's
[field_of_study] => Science
[grade_point] => 3
[criteria] => desired
)
)
Demo
you can achieve this using array_collapse.
Link
EDIT :
while tag has changed.
Here is the core php solution based on Laravel array_collapse:
function collapse($array)
{
$results = [];
foreach ($array as $values) {
if (! is_array($values)) {
continue;
}
$results = array_merge($results, $values);
}
return $results;
}
I have this array:
Array
(
[0] => Array
(
[0] => 1
[1] => a,b,c
)
[1] => Array
(
[0] => 5
[1] => d,e,f
)
)
I want the final array to be this:
Array
(
[0] => Array
(
[0] => 1
[1] => a
)
[1] => Array
(
[0] => 1
[1] => b
)
[2] => Array
(
[0] => 1
[1] => c
)
[3] => Array
(
[0] => 5
[1] => d
)
[4] => Array
(
[0] => 5
[1] => e
)
[5] => Array
(
[0] => 5
[1] => f
)
)
This is what I did:
<?php
$array = array(array(1,"a,b,c"),array(5,"d,e,f"));
$temp=array();
$count = 0;
foreach($array as $arr){
$rows = explode(",",$arr[1]);
foreach($rows as $row){
$temp[$count] = $arr;
$temp[$count][1] = $row;
$count++;
}
}
print_r($temp);
?>
This totally works but I was wondering if there was a better way to do this. This can be very slow when I have huge data.
Try like this way...
<?php
$array = array(array(1,"a,b,c"),array(5,"d,e,f"));
$temp=array();
$count = 0;
foreach($array as $arr){
$rows = explode(",",$arr[1]);
foreach($rows as $row){
$temp[$count][] = $arr[0];
$temp[$count][] = $row;
$count++;
}
}
/*print "<pre>";
print_r($temp);
print "<pre>";*/
?>
Here's a functional approach:
$result = array_merge(...array_map(function(array $a) {
return array_map(function($x) use ($a) {
return [$a[0], $x];
}, explode(",", $a[1]));
}, $array));
Try it online.
Or simply with two loops:
$result = [];
foreach ($array as $a) {
foreach (explode(",", $a[1]) as $x) {
$result[] = [$a[0], $x];
}
}
Try it online.
Timing these reveals that a simple loop construct is ~8 times faster.
functional: 4.06s user 0.08s system 99% cpu 4.160 total
loop: 0.53s user 0.05s system 102% cpu 0.561 total
If you need other way around,
$array = array(array(1, "a,b,c"), array(5, "d,e,f"));
$temp = [];
array_walk($array, function ($item, $key) use (&$temp) {
$second = explode(',', $item[1]);
foreach ($second as $v) {
$temp[] = [$item[0], $v];
}
});
print_r($temp);
array_walk — Apply a user supplied function to every member of an array
Here is working demo.
I have a $search_array like this
Array
(
[1] => Array
(
[type] => book
[search] => steve
)
[2] => Array
(
[type] => book
[search] => john
)
foreach ($search_array as $s) {
$arrayid = //???????
$searchtype = $s['type'];
$search = urlencode($s['search']);
getResult($arrayid);
}
I'm trying to figure out how to get the array number. So for the first result i need $arrayid to be 1. How do I reference that in the foreach loop?
Thanks
Use a foreach with "$key => $value"
Array
(
[1] => Array
(
[type] => book
[search] => steve
)
[2] => Array
(
[type] => book
[search] => john
)
foreach ($search_array as $key => $s) {
$arrayid = $key
$searchtype = $s['type'];
$search = urlencode($s['search']);
getResult($arrayid);
}
Adding $arrayid => in your foreach loop declaration will auto-assign $arrayid with the current array index.
foreach ($search_array as $arrayid => $s) {
// ...
getResult($arrayid);
}
See foreach on PHP Manual.
foreach ($search_array as $arrayid => $s) {
Please read PHP documentation before asking such basic questions
foreach ($search_array as $arrayid => $s) {
// your code here
}
This is a way you could retrieve data from a Php array. It will retrieve all entries from array $value and their key $key.
foreach ($array as $key => $value) {
// $key is the array index
}
I have an array structure like this, which I'm able to print out just fine:
Array
(
[0] => Array
(
[title] => blah
[author] => Bob
[link] => randomlink
)
[1] => Array
(
[title] => random
[author] => George
[link] => randomlink
)
[2] => Array
(
[title] => blah
[author] => Bob
[link] => randomlink
)
)
Basically, I want to be able to print out only the information in the array that's related to the 'author' 'Bob'. As you can see, he has two items in there. When I print out the array, it should only show the 0 and 2 array since those are the only ones that contain the 'author' which is 'Bob'. Any ideas?
foreach ($array as $a)
{
if($a['author'] === 'Bob') {
echo $a['title'];
echo $a['author'];
echo $a['link'];
}
}
foreach($arr as $item)
{
if($item['author'] != 'Bob')
{
continue;
}
// print out Bob's stuff
}
This is the code:
foreach($array as $subarray)
{
if(strcasecmp($subarray['author'],'Bob') === 0)
print_r($subarray);
}
Simply foreach
foreach ($array as $item) {
if ($item['author']) {
// Do something with $item
}
}
ok ! try this :
for($i=0;$i<count($array);$i++){
if($array[$i]['author'] == 'bob'){
echo $array[$i]['title']." > ".$array[$i]['author']." > ".$array[$i]['link']."\r\n<br>";
}
}
...