I need to modify an array with subarrays and keep only the top two arrays (array -> results - x) and remove any subarray below. For example array "location" & "syncState" should be removed.
Original array:
$device_array = [
"totalCount" => "3",
"results" => [
[
"id" => "2",
"serialNumber" => "DX",
"location" => ["id" => "5", "locationName" => "US"]
],
[
"id" => "4",
"serialNumber" => "DM",
"syncState" => ["id" => "7", "locationName" => "DE"]
],
[
"id" => "5",
"serialNumber" => "C0"
]
]
];
The array should look like this:
Array
(
[totalCount] => 3
[results] => Array
(
[0] => Array
(
[id] => 2
[serialNumber] => DX
)
[1] => Array
(
[id] => 4
[serialNumber] => DM
)
[2] => Array
(
[id] => 5
[serialNumber] => C0
)
)
)
I'm trying to loop through the arrays (sub arrays included) but I can't remove all of the subarrays that sit under $device_array['results'][x].
foreach ($device_array as $key => $value) {
if(is_array($value)) {
unset($device_array['results'][0]['location']);
}
}
You can just loop the results subarray directly and write a custom filter which will modify each entry by reference. Any of the associative elements that hold array type data will be filtered out.
Code: (Demo)
$array = [
"totalCount" => "3",
"results" => [
[
"id" => "2",
"serialNumber" => "DX",
"location" => ["id" => "5", "locationName" => "US"]
],
[
"id" => "4",
"serialNumber" => "DM",
"syncState" => ["id" => "7", "locationName" => "DE"]
],
[
"id" => "5",
"serialNumber" => "C0"
]
]
];
foreach ($array['results'] as &$entry) {
$entry = array_filter($entry, 'is_scalar');
}
var_export($array);
Output:
array (
'totalCount' => '3',
'results' =>
array (
0 =>
array (
'id' => '2',
'serialNumber' => 'DX',
),
1 =>
array (
'id' => '4',
'serialNumber' => 'DM',
),
2 =>
array (
'id' => '5',
'serialNumber' => 'C0',
),
),
)
Or completely functional style: (Demo)
$array['results'] = array_map(
function($entry) {
return array_filter($entry, 'is_scalar');
},
$array['results']
);
var_export($array);
This is how you obtain the output, but I am not so sure if this is what you need in your case
<?php
$array = [
'total' => 2,
'result' => [
[
'id' => 1,
'serialNumber' => 'DX',
'location' => ['id'=>1, 'locationName'=>'US']
],
[
'id' => 2 ,
'serialNumber' => 'DO',
'syncState' => ['id'=>7, 'locationName'=>'DE']
]
]
];
foreach( $array['result'] as $key => $value ){
foreach($value as $key2=>$subarray){
if(is_array($subarray)){
unset($value[$key2]);
}
}
$array['result'][$key] = $value;
}
print_r($array);
i am facing problem in storing work and education information of Facebook user.
this is how i am getting info of user:
$profile_request=$fb->get('/me?fields=name,first_name,last_name,email,work,education');
and then convert the response in to multidimensional array:
$profile = $profile_request->getGraphNode()->asArray();
this is how i get the response:
$profile=Array
(
"name" => "abc pqr",
"first_name" => "abc",
"last_name" => "pqr",
"email" => "abc#gmail.com",
"work" => Array
(
"0" => Array
(
"employer" => Array
(
"id" => "348468651959125",
"name" => "Karachi university"
),
"location" => Array
(
"id" => "110713778953693",
"name" => "Karachi, Pakistan"
),
"position" => Array
(
"id" => "1556082398000870",
"name" => "Lecturer"
),
"start_date" => "2008-04-25"
),
"1" => Array
(
"description" => "i am teaching......",
"end_date" => "2011-06-20",
"employer" => Array
(
"id" => "486743441453589",
"name" => "Happy Palace Grammar School NORTH 3 - J2"
),
"location" => Array
(
"id" => "110713778953693",
"name" => "Karachi, Pakistan"
),
"position" => Array
(
"id" => "1556082398000870",
"name" => "Lecturer"
),
"start_date" => "2005-06-17"
)
),
"education" => Array
(
"0" => Array
(
"school" => Array
(
"id" => "193563427344550",
"name" => "Mehran Model Sec School"
),
"type" => "High School"
),
"1" => Array
(
"concentration" => Array
(
"0" => Array
(
"id" => "104076956295773",
"name" => "Computer Science"
)
),
"school" => Array
(
"id" => "113340788773685",
"name" => "Sir Adamjee Institute"
),
"type" => "College",
"year" => Array
(
"id" => "118118634930920",
"name" => "2012"
)
),
"2" => Array
(
"concentration" => Array
(
"0" => Array
(
"id" => "104076956295773",
"name" => "Computer Science"
)
),
"degree" => Array
(
"id" => "519451718218292",
"name" => "Bachelor of science in Computer Science in Computer Science"
),
"school" => Array
(
"id" => "107345492681211",
"name" => "SZABIST"
),
"type" => "Graduate School",
"year" => Array
(
"id" => "127342053975510",
"name" => "2016"
)
)
),
"id" => "145864899647476"
);
and this is my code:
$keys = array_keys($profile);
print_r($keys);
echo count($profile);
echo "<br>";
for ($i=4; $i <count($profile)-1 ; $i++) {
# code...
/*[4] => work [5] => education*/
echo $keys[$i]."<br>";
foreach ($profile[$keys[$i]] as $k => $v) {
# code...
echo "<br>$k<br>";
$keeys=array_keys($v);
print_r($keeys);
}
}
Lets say, I have the following array:
$array = array(
array(
"id" => 1,
"name" => "Europe",
"path" => "/"
),
array(
"id" => 2,
"name" => "Germany",
"path" => "/1/"
),
array(
"id" => 3,
"name" => "France",
"path" => "/1/"
),
array(
"id" => 4,
"name" => "Berlin",
"path" => "/1/2/"
),
array(
"id" => 5,
"name" => "Munich",
"path" => "/1/2/"
)
);
As you can see, its a multidimensional array with 3 properites in earch 2nd level array: id, name and path. The path is a path structure based on the parent-id of its parent. For example, Germany (id=2) has belongs to Europe, so the path is "/1/" (ID 1 = Europe) and Berlin in Germany has the path "/1/2/" which means "/Europe/Germany/"
Now, I am trying to create a tree-array out of this, which should somehow look like:
$result = array(
1 => array(
"id" => 1,
"name" => "Europe",
"path" => "/",
"childs" => array(
2 => array(
"id" => 2,
"name" => "Germany",
"path" => "/1/",
"childs" => array(
4 => array(
"id" => 4,
"name" => "Berlin",
"path" => "/1/2/"
),
5 => array(
"id" => 5,
"name" => "Munich",
"path" => "/1/2/"
)
)
),
3 => array(
"id" => 3,
"name" => "France",
"path" => "/1/"
)
)
)
);
I have already tried to create a function with internal references, but this didn't works for me:
public static function pathToTree($items) {
$array = array();
$result = array();
foreach($items AS $res) {
$ids = explode("/", ltrim($res["path"] . $res["id"], "/"));
$count = count($ids);
$tmp = &$result;
foreach( $ids AS $id) {
if($count == 1) {
$tmp = $res;
$tmp["childs"] = array();
$tmp = &$tmp["childs"];
}
else {
$tmp[$id] = array(
"childs" => array()
);
$tmp = &$tmp[$id]["childs"];
}
$count--;
}
}
return $array;
}
Ok, I think I just found a solution:
function pathToTree($array){
$tree = array();
foreach($array AS $item) {
$pathIds = explode("/", ltrim($item["path"], "/") . $item["id"]);
$current = &$tree;
foreach($pathIds AS $id) {
if(!isset($current["childs"][$id])) $current["childs"][$id] = array();
$current = &$current["childs"][$id];
if($id == $item["id"]) {
$current = $item;
}
}
}
return $tree["childs"];
}
This is a dynamice solution for 1-n depth. Look at my example at http://ideone.com/gn0XLp . Here I tested it with some level:
Continent
Country
City
City-District
City-Subdistrict
City Sub-Sub-District
I've created a recursive function:
// The array
$array = array(
array(
"id" => 1,
"name" => "Europe",
"path" => "/"
),
array(
"id" => 2,
"name" => "Germany",
"path" => "/1/"
),
array(
"id" => 3,
"name" => "France",
"path" => "/1/"
),
array(
"id" => 4,
"name" => "Berlin",
"path" => "/1/2/"
),
array(
"id" => 5,
"name" => "Munich",
"path" => "/1/2/"
),
array(
"id" => 6,
"name" => "Asia",
"path" => "/"
),
array(
"id" => 7,
"name" => "India",
"path" => "/6/"
),
array(
"id" => 7,
"name" => "Mumbai",
"path" => "/6/7"
),
array(
"id" => 8,
"name" => "Delhi",
"path" => "/6/7"
),
);
// The recursive function
function createTree($input, &$result = array(), $key = null) {
if ($key == "id") {
$result["temp"]["id"] = $input;
}
if ($key == "name") {
$result["temp"]["name"] = $input;
}
if ($key == "path") {
$result["temp"]["path"] = $input;
$levels = is_string($input) ? array_values(array_filter(explode('/', $input))) : null;
if ($input == "/") {
$result[$result["temp"]["id"]] = $result["temp"];
}
if (count($levels) == 1) {
$result[$levels[0]]["childs"][$result["temp"]["id"]] = $result["temp"];
}
if (count($levels) == 2) {
$result[$levels[0]]["childs"][$levels[1]]["childs"][$result["temp"]["id"]] = $result["temp"];
}
unset($result["temp"]);
}
if (is_array($input)) {
foreach($input as $key => $value) {
createTree($value, $result, $key);
}
}
return $result;
}
// The result
array (
1 =>
array (
'id' => 1,
'name' => 'Europe',
'path' => '/',
'childs' =>
array (
2 =>
array (
'id' => 2,
'name' => 'Germany',
'path' => '/1/',
'childs' =>
array (
4 =>
array (
'id' => 4,
'name' => 'Berlin',
'path' => '/1/2/',
),
5 =>
array (
'id' => 5,
'name' => 'Munich',
'path' => '/1/2/',
),
),
),
3 =>
array (
'id' => 3,
'name' => 'France',
'path' => '/1/',
),
),
),
6 =>
array (
'id' => 6,
'name' => 'Asia',
'path' => '/',
'childs' =>
array (
7 =>
array (
'id' => 7,
'name' => 'India',
'path' => '/6/',
'childs' =>
array (
7 =>
array (
'id' => 7,
'name' => 'Mumbai',
'path' => '/6/7',
),
8 =>
array (
'id' => 8,
'name' => 'Delhi',
'path' => '/6/7',
),
),
),
),
),
)
As I said in the comment, you need at least three loops to achieve your goals. Here's the function:
function pathToTree($array){
$tree = Array();
for($i=0; $i < count($array); $i++){
if(substr_count($array[$i]["path"], '/') == 1)
$tree[$array[$i]["id"]] = $array[$i];
}
for($i=0; $i < count($array); $i++){
if(substr_count($array[$i]["path"], '/') == 2){
$num = (int)str_replace("/","",$array[$i]["path"]);
$tree[$num]["childs"][$array[$i]["id"]] = $array[$i];
}
}
for($i=0; $i < count($array); $i++){
if(substr_count($array[$i]["path"], '/') == 3){
$num = explode("/", $array[$i]["path"]);
$tree[$num[1]]["childs"][$num[2]]["childs"][$array[$i]["id"]] = $array[$i];
}
}
return $tree;
}
Example:
Consider this array:
$array = array(
array(
"id" => 1,
"name" => "Europe",
"path" => "/"
),
array(
"id" => 2,
"name" => "Germany",
"path" => "/1/"
),
array(
"id" => 3,
"name" => "France",
"path" => "/1/"
),
array(
"id" => 4,
"name" => "Berlin",
"path" => "/1/2/"
),
array(
"id" => 5,
"name" => "Munich",
"path" => "/1/2/"
),
array(
"id" => 6,
"name" => "Asia",
"path" => "/"
),
array(
"id" => 7,
"name" => "China",
"path" => "/6/"
),
array(
"id" => 8,
"name" => "Bangladesh",
"path" => "/6/"
),
array(
"id" => 9,
"name" => "Beijing",
"path" => "/6/7/"
),
array(
"id" => 10,
"name" => "Dhaka",
"path" => "/6/8/"
)
);
if I ran this code:
print_r(pathToTree($array));
the output will be:
Array
(
[1] => Array
(
[id] => 1
[name] => Europe
[path] => /
[childs] => Array
(
[2] => Array
(
[id] => 2
[name] => Germany
[path] => /1/
[childs] => Array
(
[4] => Array
(
[id] => 4
[name] => Berlin
[path] => /1/2/
)
[5] => Array
(
[id] => 5
[name] => Munich
[path] => /1/2/
)
)
)
[3] => Array
(
[id] => 3
[name] => France
[path] => /1/
)
)
)
[6] => Array
(
[id] => 6
[name] => Asia
[path] => /
[childs] => Array
(
[7] => Array
(
[id] => 7
[name] => China
[path] => /6/
[childs] => Array
(
[9] => Array
(
[id] => 9
[name] => Beijing
[path] => /6/7/
)
)
)
[8] => Array
(
[id] => 8
[name] => Bangladesh
[path] => /6/
[childs] => Array
(
[10] => Array
(
[id] => 10
[name] => Dhaka
[path] => /6/8/
)
)
)
)
)
)
Here's the phpfiddle link in case you might try it yourself.
I have array
$data = array(
0 => array( "id" => 2, "status" => 1),
1 => array( "name" => "you", "class" => "expert"),
);
I want result
$result = array(
"id" => 2,
"status" => 1,
"name" => "you",
"class" => "expert"
);
How to solved it ?
Here is a simple solution for this case:
$data = array(
0 => array( "id" => 2, "status" => 1),
1 => array( "name" => "you", "class" => "expert"),
);
$result = array_merge($data[0], $data[1]);
print_r($result);
Result:
Array
(
[id] => 2
[status] => 1
[name] => you
[class] => expert
)
You can simply use call_user_func_array function of PHP as
$result_array = call_user_func_array('array_merge', $data);
print_r($result_array);
I have this kind of array which I want it to be populated with values from MySQL db. For example if there are 5 rows in the database, it should loop the array 5 times together with the values in it.
This is how my current array (to be parsed in JSON) looks like:
array(
1 => array(
"id" => 1,
"category" => "For men",
"items" => array(
array(
"id" => 1,
"name" => "Baju",
"price" => "5:52"
),
array(
"id" => 2,
"name" => "The Canyon",
"price" => "3:01"
)
)
),
2 => array(
"id" => 2,
"category" => "Adele 21",
"items" => array(
array(
"id" => 1,
"name" => "Rolling In The Deep",
"price" => "03:48"
),
array(
"id" => 2,
"name" => "Rumour Has It",
"price" => "03:43"
)
)
)
),
.
.
.
. //more arrays here;
So I did a while loop to print out (print_r()) the array according from my database. It looks like this:
Array (
[0] => Array (
[id] => 1
[item_photo] => gambar1
[item_name] => Kotak
[item_description] => Desc 1 - Lorem ipsum blablabla
[user_id] => 6
[category_id] => 2
)
[1] => Array (
[id] => 2
[item_photo] => gambar2
[item_name] => Botol
[item_description] => Desc 2 - Lorem ipsum blablabla
[user_id] => 6
[category_id] => 3
)
[n] . . .
.
.
.
)
What I wanna achieve is to replace the values in the first array (to be parsed in JSON) with the one in array two. Like so,
array(
$category_id => array(
"id" => $i++,
"category" => $category_name,
"items" => array(
array(
"id" => $j++,
"user_name" => $user_name,
"name" => $item_name,
"price" => $price,
"item_description" => $item_description
)
)
),
); //notice the variables
This is only just a sketching of the idea of what I want to achieve. But I couldn't wrap my head around this to make it work.
Any idea how to populate the first array according to the second array's value?