Related
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'm retrieving some JSON that I am converting to an associative array. The issue that I am having is I am trying to get the email value from the user's who id matches the value that I have already set as a variable.
Here is what the array looks like
Array
(
[object] => list
[data] => Array
(
[0] => Array
(
[object] => pro
[id] => pro_77c9c6a85d814e059a6a2690989bae29
[first_name] => Jane
[last_name] => Doe
[full_name] => Jane Doe
[initials] => JD
[email] => admin#testorg.com
[mobile_number] => 9998761234
[messaging_uuid] => 4547c231c3e7d0ff1796f47b88f166d5
[color_hex] => EF9159
[avatar_url] => /assets/add_image.png
[avatar_thumb_url] =>
[has_avatar] =>
[organization_name] => testorg
[is_admin] => 1
[permissions] => Array
(
[show_company_setup] => 1
[can_see_home_data] => 1
[show_reporting] => 1
)
[is_super_pro] =>
[is_archived] =>
[impersonated] =>
)
[1] => Array
(
[object] => pro
[id] => pro_0fcb8e8610e54c518078db77ced7530e
[first_name] => Robert
[last_name] => Jordan
[full_name] => Robert Jordan
[initials] => RJ
[email] => rj#testorg.com
[mobile_number] => 4547457742
[messaging_uuid] => 0fcb8e8610e54c518078db77ced7530e
[color_hex] => EF9159
[avatar_url] => /assets/add_image.png
[avatar_thumb_url] =>
[has_avatar] =>
[organization_name] => testorg
[is_admin] => 1
[permissions] => Array
(
[show_company_setup] => 1
[can_see_home_data] => 1
[show_reporting] => 1
)
[is_super_pro] =>
[is_archived] =>
[impersonated] =>
)
)
[url] => /pros
)
Im basically trying to match the value that I have set in my pro_id variable
pro_0fcb8e8610e54c518078db77ced7530e
To the 'ID' Key in the array above and get the 'email' value associated to that same array and store for use later in my code.
Here is what I have so far, but no joy
foreach ($proObject as $key => $value) {
if ($key['id'] == $pro_id)
$techmail = $key['email'];
}
From my understanding of your question, and if you want to get only one element, you should be able to use array_search with array_column to get the index of the searched element. Using that you can then access the element and its corresponding email value. If you might expect more than one element I would use array_filter.
One Element:
In short:
$i = array_search($pro_id, array_column($proObject, 'id'));
$element = ($i !== false ? $proObject[$i] : null);
print_r($element["email"]);
Full code:
<?php
$proObject = array(
array(
"object" => "pro",
"id" => "pro_77c9c6a85d814e059a6a2690989bae29",
"first_name" => "Jane",
"last_name" => "Doe",
"full_name" => "Jane Doe",
"initials" => "JD",
"email" => "admin#testorg.com",
"mobile_number" => "9998761234",
"messaging_uuid" => "4547c231c3e7d0ff1796f47b88f166d5",
"color_hex" => "EF9159",
"avatar_url" => "/assets/add_image.png",
"avatar_thumb_url" => "",
"has_avatar" => "",
"organization_name" => "testorg",
"is_admin" => "1",
"permissions" => array(
"show_company_setup" => "1",
"can_see_home_data" => "1",
"show_reporting" => "1",
) ,
"is_super_pro" => "",
"is_archived" => "",
"impersonated" => "",
) ,
array(
"object" => "pro",
"id" => "pro_0fcb8e8610e54c518078db77ced7530e",
"first_name" => "Robert",
"last_name" => "Jordan",
"full_name" => "Robert Jordan",
"initials" => "RJ",
"email" => "rj#testorg.com",
"mobile_number" => "4547457742",
"messaging_uuid" => "0fcb8e8610e54c518078db77ced7530e",
"color_hex" => "EF9159",
"avatar_url" => "/assets/add_image.png",
"avatar_thumb_url" => "",
"has_avatar" => "",
"organization_name" => "testorg",
"is_admin" => "1",
"permissions" => array(
"show_company_setup" => "1",
"can_see_home_data" => "1",
"show_reporting" => "1",
) ,
"is_super_pro" => "",
"is_archived" => "",
"impersonated" => "",
)
);
$pro_id = "pro_0fcb8e8610e54c518078db77ced7530e";
$i = array_search($pro_id, array_column($proObject, 'id'));
$element = ($i !== false ? $proObject[$i] : null);
print_r($element["email"]);
?>
Multiple Elements:
In short:
class idEqualsFilter {
private $id;
public function __construct($id) {
$this->id = $id;
}
function __invoke($i) {
return $this->id === $i["id"];
}
};
$elements = array_filter($proObject, new idEqualsFilter($pro_id));
print_r(array_column($elements, "email"));
Full code:
<?php
$proObject = array(
array(
"object" => "pro",
"id" => "pro_77c9c6a85d814e059a6a2690989bae29",
"first_name" => "Jane",
"last_name" => "Doe",
"full_name" => "Jane Doe",
"initials" => "JD",
"email" => "admin#testorg.com",
"mobile_number" => "9998761234",
"messaging_uuid" => "4547c231c3e7d0ff1796f47b88f166d5",
"color_hex" => "EF9159",
"avatar_url" => "/assets/add_image.png",
"avatar_thumb_url" => "",
"has_avatar" => "",
"organization_name" => "testorg",
"is_admin" => "1",
"permissions" => array
(
"show_company_setup" => "1",
"can_see_home_data" => "1",
"show_reporting" => "1",
),
"is_super_pro" => "",
"is_archived" => "",
"impersonated" => "",
),
array(
"object" => "pro",
"id" => "pro_0fcb8e8610e54c518078db77ced7530e",
"first_name" => "Robert",
"last_name" => "Jordan",
"full_name" => "Robert Jordan",
"initials" => "RJ",
"email" => "rj#testorg.com",
"mobile_number" => "4547457742",
"messaging_uuid" => "0fcb8e8610e54c518078db77ced7530e",
"color_hex" => "EF9159",
"avatar_url" => "/assets/add_image.png",
"avatar_thumb_url" => "",
"has_avatar" => "",
"organization_name" => "testorg",
"is_admin" => "1",
"permissions" => array
(
"show_company_setup" => "1",
"can_see_home_data" => "1",
"show_reporting" => "1",
),
"is_super_pro" => "",
"is_archived" => "",
"impersonated" => "",
)
);
$pro_id = "pro_0fcb8e8610e54c518078db77ced7530e";
class idEqualsFilter {
private $id;
public function __construct($id) {
$this->id = $id;
}
function __invoke($i) {
return $this->id === $i["id"];
}
};
$elements = array_filter($proObject, new idEqualsFilter($pro_id));
print_r(array_column($elements, "email"));
?>
I am having a hard time figuring out how to modify my array. The original array is this...
$array = array(
array(
"fruit" => "pineapple",
"id" => "aaa",
),
array(
"fruit" => "orange",
"id" => "aaa",
),
array(
"fruit" => "apple",
"id" => "bbb",
),
array(
"fruit" => "pear",
"id" => "bbb",
),
array(
"fruit" => "peach",
"id" => "ccc",
),
array(
"fruit" => "melon",
"id" => "ccc",
)
);
I need to convert this array into an array of keys by id. For example I would want the end result to look like this...
$array = array(
"aaa" => array("pineapple", "orange"),
"bbb" => array("apple", "pear"),
"ccc" => array("peach", "melon"),
);
I have attempted to loops through the array and pull out the things I need and rebuild the array but I cant figure it out. Hopefully someone can help me. Thanks!
You can do it by making a new array this way:
$array = array(
array(
"fruit" => "pineapple",
"id" => "aaa",
),
array(
"fruit" => "orange",
"id" => "aaa",
),
array(
"fruit" => "apple",
"id" => "bbb",
),
array(
"fruit" => "pear",
"id" => "bbb",
),
array(
"fruit" => "peach",
"id" => "ccc",
),
array(
"fruit" => "melon",
"id" => "ccc",
)
);
// empty array
$result = [];
// loop trough data
foreach($array as $value){
// add item to the $result array. Then make the id the key and the fruit the value
$result[$value['id']][] = $value['fruit'];
}
//print array
print_r($result);
The result will be
Array ( [aaa] => Array ( [0] => pineapple [1] => orange ) [bbb] => Array ( [0] => apple [1] => pear ) [ccc] => Array ( [0] => peach [1] => melon ) )
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.
Does any on know how can I convert this
$events = array(
array("type" => "off-site", "title" => "aaa", "nid" => "11"),
array("type" => "off-site", "title" => "bbb", "nid" => "22"),
array("type" => "installation", "title" => "ccc", "nid" => "33"),
array("type" => "opening", "title" => "ddd", "nid" => "44"),
array("type" => "opening", "title" => "eee", "nid" => "55"),
array("type" => "opening", "title" => "fff", "nid" => "66")
);
into this
$events_processed = array(
"off-site" => array(
array(
"title" => "aaa",
"nid" => "11"
),
array(
"title" => "bbb",
"nid" => "22"
)
),
"installation" => array(
array(
"title" => "ccc",
"nid" => "33"
)
),
"opening" => array(
array(
"title" => "ddd",
"nid" => "44"
),
array(
"title" => "eee",
"nid" => "55"
),
array(
"title" => "fff",
"nid" => "66"
)
)
);
using php?
I've already tried to apply different methods from different posts here but with no success.
I need the array to be nested so I can reorder the array by "type".Hi
You can the code below, please note that your current output is not valid because you missed the array index ...
Example 1
$events_processed = array();
foreach($events as $options)
{
$events_processed[$options['type']][] = array("title"=>$options['title'],"nid"=>$options['nid']);
}
var_dump($events_processed);
OR
Example 2 (#dleiftah suggestion)
$defautKey = "type" ;
foreach($events as $options)
{
$type = $options[$defautKey] ;
unset($options[$defautKey]);
$events_processed[$type][] = $options;
}
var_dump($events_processed);
Both Result Would be Like this but number 2 is more flexible
array
'off-site' =>
array
0 =>
array
'title' => string 'aaa' (length=3)
'nid' => string '11' (length=2)
1 =>
array
'title' => string 'bbb' (length=3)
'nid' => string '22' (length=2)
'installation' =>
array
0 =>
array
'title' => string 'ccc' (length=3)
'nid' => string '33' (length=2)
'opening' =>
array
0 =>
array
'title' => string 'ddd' (length=3)
'nid' => string '44' (length=2)
1 =>
array
'title' => string 'eee' (length=3)
'nid' => string '55' (length=2)
2 =>
array
'title' => string 'fff' (length=3)
'nid' => string '66' (length=2)
Just loop through and reorganize ...
$result = array();
foreach($events as $event){
$key = $event['type'];
unset($event['type']);
$result[$key][] = $event;
}
print_r($result);
Here's what I did:
$array_processed = array();
foreach( $events as $evt){
$array_processed[$evt['type']][] = array('title'=>$evt['title'], 'nid'=>$evt['nid']);
}
print_r($array_processed);
There is no built in function that will do this. You will have to loop through this array and make a new array.
$events=array(contents-of-array);
$proc_events=array(
'off-site' => array(),
'installation' => array(),
'opening' => array()
);
foreach($events as $key => $value)
{
switch($value['type'])
{
case 'off-site':
$proc_events['offsite']=array('title' => $value['title'], 'nid' => $value['nid']);
break;
case 'installation':
$proc_events['installation']=array('title' => $value['title'], 'nid' => $value['nid']);
break;
case 'opening':
$proc_events['opening']=array('title' => $value['title'], 'nid' => $value['nid']);
break;
}
}
The above should work.
The shortest code to do this should be:
foreach ($events as $event)
$events_processed[$event['type']][] = array('title' => $event['title'], 'nid' => $event['nid']);
Here is what I was able to do:
<?php
$events = array(
array("type" => "off-site", "title" => "aaa", "nid" => "11"),
array("type" => "off-site", "title" => "bbb", "nid" => "22"),
array("type" => "installation", "title" => "ccc", "nid" => "33"),
array("type" => "opening", "title" => "ddd", "nid" => "44"),
array("type" => "opening", "title" => "eee", "nid" => "55"),
array("type" => "opening", "title" => "fff", "nid" => "66")
);
foreach ($events as $event) {
$events_processed[$event['type']][] = array('title' => $event['title'],
'nid' => $event['nid']
);
}
echo '<pre>';
print_r($events_processed);
?>
This prints the following:
Array
(
[off-site] => Array
(
[0] => Array
(
[title] => aaa
[nid] => 11
)
[1] => Array
(
[title] => bbb
[nid] => 22
)
)
[installation] => Array
(
[0] => Array
(
[title] => ccc
[nid] => 33
)
)
[opening] => Array
(
[0] => Array
(
[title] => ddd
[nid] => 44
)
[1] => Array
(
[title] => eee
[nid] => 55
)
[2] => Array
(
[title] => fff
[nid] => 66
)
)
)