Insert an array to a specified location in named array - php

In the array below, how can I push the new array into the $options array at the specified location?
$options = array (
array( "name" => "My Options",
"type" => "title"),
array( "type" => "open"),
array("name" => "Test",
"desc" => "Test",
"id" => $shortname."_theme",
"type" => "selectTemplate",
"options" => $mydir ),
//I want the pushed array inserted here.
array("name" => "Test2",
"desc" => "Test",
"id" => "test2",
"type" => "test",
"options" => $mydir ),
array( "type" => "close")
);
if(someCondition=="met")
{
array_push($options, array( "name" => "test",
"desc" => "description goes here",
"id" => "testMet",
"type" => "checkbox",
"std" => "true"));
}

You can use array_splice. For your example:
if($some_condition == 'met') {
// splice new option into array at position 3
array_splice($options, 3, 0, array($new_option));
}
Note: array_splice expects the last parameter to be an array of new elements, so for your example you need to pass an array containing the new option's array.

Simply
array_splice($options, 3, 0, $newArr);

for insert a new array, not to a spesific location(between $r[4] and $r[5]):
$options[]=array ("key" => "val"); //insert new array
$options[]=$v; //insert new variable
to insert a new array after spesific variable:
function array_push(&$array,$after_element_number,$new_var)
{
array_splice($array, $after_element_number, 0, $new_var);
}
if(someCondition=="met")
{
array_push($options, 2, array( "name" => "test",
"desc" => "description goes here",
"id" => "testMet",
"type" => "checkbox",
"std" => "true"));
}

As connec says, you can use array_splice, but without forgetting to wrap your array in another array, like this:
if ('met' === $some_condition)
{
array_splice($options, 3, 0, array(array(
'name' => 'test',
'desc' => 'description goes here',
'id' => 'testMet',
'type' => 'checkbox',
'std' => 'true'
)));
}
Edit: connec has already specified its response.

Related

Recursively getting a list of parents for each node in a nested PHP array

In PHP I have a set of nested arrays of data. I want to flatten these, so that for every node and leaf I get a list of its parents.
Here's an example of the original array - note, each part could be of an unknown depth and length:
$data = array(
"name" => "Thing",
"children" => array(
array(
"name" => "Place",
"rdfs:subClassOf" => "schema:Thing",
"children" => array(
array(
"name" => "Accomodation",
"rdfs:subClassOf" => "schema:Place",
"children" => array(
array(
"name" => "Apartment",
"rdfs:subClassOf" => "schema:Accomodation",
),
array(
"name" => "Hotel",
"rdfs:subClassOf" => "schema:Accomodation",
),
array(
"name" => "House",
"rdfs:subClassOf" => "schema:Accomodation",
)
)
)
)
),
array(
"name" => "CreativeWork",
"rdfs:subClassOf" => "schema:Thing",
"children" => array(
array(
"name" => "Article",
"rdfs:subClassOf" => "schema:CreativeWork",
"children" => array(
array(
"name" => "NewsArticle",
"rdfs:subClassOf" => "schema:Article",
),
array(
"name" => "OpinionArticle",
"rdfs:subClassOf" => "schema:Article",
),
)
)
)
)
)
);
(The data I'm actually parsing is this Schema.org JSON file - the above is a minimal example of it.)
And here's what I'd like to end up with:
$results = array(
"Place" => array("Thing"),
"Accomodation" => array("Thing", "Place"),
"Apartment" => array("Thing", "Place", "Accomodation"),
"Hotel" => array("Thing", "Place", "Accomodation"),
"House" => array("Thing", "Place", "Accomodation"),
"CreativeWork" => array("Thing"),
"Article" => array("Thing", "CreativeWork"),
"NewsArticle" => array("Thing", "CreativeWork", "Article"),
"OpinionArticle" => array("Thing", "CreativeWork", "Article"),
);
I'm assuming I need to recursively call a function to build the array but so far I'm not having much luck. In case this makes it harder, this is happening in a static method.
Something quick to get you started:
class Parser {
public static function parse($input,$prefix = []) {
$return = $prefix ? [$input['name']=>$prefix] : [];
if (isset($input['children'])) {
$prefix[] = $input['name'];
foreach ($input['children'] as $child) {
$return += self::parse($child,$prefix);
}
}
return $return;
}
}
var_dump(Parser::parse($data));
You probably need to add a few checks and comments to make it more readable.

Construct an associative array from 2 other arrays, and linked by a common key

Problem:
I would like to combine 2 associative arrays to make one. To link these arrays, the ID key is present in both.
Input:
To retrieve my contacts with api call, I have to do 2 requests :
First to retrieve contacts with Id, and email adresse
Second to get some informations like name, city etc.
The first one return an array like this :
$contactArray = array(
array(
"CreatedAt" => "2019-04-12T11:53:26Z",
"DeliveredCount" => 0,
"Email" => "terry#example.org",
"ExclusionFromCampaignsUpdatedAt" => "2019-04-28T09:21:35Z",
"ID" => 1864410583,
"IsExcludedFromCampaigns" => false,
"IsOptInPending" => false,
"IsSpamComplaining" => false,
"LastActivityAt" => "2019-04-28T09:21:35Z",
"LastUpdateAt" => "2019-04-28T09:21:35Z",
"Name" => "",
"UnsubscribedAt" => "",
"UnsubscribedBy" => ""
),
array(
"CreatedAt" => "2019-04-12T12:39:30Z",
"DeliveredCount" => 0,
"Email" => "duane#example.org",
"ExclusionFromCampaignsUpdatedAt" => "",
"ID" => 1864410588,
"IsExcludedFromCampaigns" => false,
"IsOptInPending" => false,
"IsSpamComplaining" => false,
"LastActivityAt" => "2019-04-12T12:39:30Z",
"LastUpdateAt" => "2019-04-12T12:39:30Z",
"Name" => "",
"UnsubscribedAt" => "",
"UnsubscribedBy" => ""
)
);
The second call, return an array like
$contactDataArray =
array(
array(
"ContactID" => 1864410583,
"Data" => array(
array(
"Name" => "firstname",
"Value" => "Mark"
),
array(
"Name" => "city",
"Value" => "Miami"
),
array(
"Name" => "name",
"Value" => "Terry"
),
array(
"Name" => "phone",
"Value" => "555-5555"
)
),
"ID" => 1864410583
),
array(
"ContactID" => 1864410588,
"Data" => array(
array(
"Name" => "firstname",
"Value" => "Jane"
),
array(
"Name" => "city",
"Value" => "New York"
),
array(
"Name" => "name",
"Value" => "Duane"
),
array(
"Name" => "phone",
"Value" => "555-5555"
)
),
"ID" => 1864410588
)
);
In $contactArray, the ID key matches with ContactID key and ID key in $contactDataArray
Attempt:
I want an array formatted like this :
$output = array(
array(
"Email" => "terry#example.org",
"ID" => 1864410583,
"firstname" => "Mark",
"city" => "Miami",
"name" => "Terry",
"phone" => "555-5555"
),
array(
"Email" => "duane#example.org",
"ID" => 1864410588,
"firstname" => "Jane",
"city" => "New York",
"name" => "Duane",
"phone" => "555-5555"
)
);
I'm trying to achieve this with array_walk, but no succeed.
You can do this with foreach,
$result = [];
foreach ($contactDataArray as $key => $value) {
$ids = array_column($contactArray, "ID"); // fetching all values from contactArray
if (!empty(array_intersect([$value['ContactID'], $value['ID']], $ids))) { // checking if both satisfy the condition
$result[$key] = array_column($value['Data'], 'Value', 'Name'); // combining name and value
// searchng for key with matched ContactID
$result[$key]['Email'] = $contactArray[array_search($value["ContactID"], $ids)]['Email'];
$result[$key]['ID'] = $value["ContactID"];
}
}
Demo.
Can you please try with this?
$output = [];
for($i = 0; $i < count($contactDataArray); $i++) {
$arrIDandEmail = [
'Email' => isset($contactArray[$i]['Email']) ? $contactArray[$i]['Email'] : '',
'ID' => isset($contactDataArray[$i]['ID']) ? $contactDataArray[$i]['ID'] : ''
];
$arrData = array_column($contactDataArray[$i]["Data"], "Value", "Name");
$newArray = array_merge($arrIDandEmail, $arrData);
$output[] = $newArray;
}
For PHP >= 7.1 you can use array destructuring using list()
<?php
$output = [];
foreach ($contactDataArray as [
'ID' => $id,
'Data' => [
['Name' => $firstnameKey, 'Value' => $firstnameValue],
['Name' => $cityKey, 'Value' => $cityValue],
['Name' => $nameKey, 'Value' => $nameValue],
['Name' => $phoneKey, 'Value' => $phoneValue]
]
]) {
$output[] = [
"Email" => $contactArray[array_search($id, array_column($contactArray, 'ID'))]['Email'],
"ID" => $id,
$firstnameKey => $firstnameValue,
$cityKey => $cityValue,
$nameKey => $nameValue,
$phoneKey => $phoneValue
];
}
var_dump($output);
Demo
You can use array_walk,array_combine,array_column for the desired array as a result
$res = [];
array_walk($contactArray, function($v, $k) use ($contactDataArray,&$res)
{
$res[] = array_merge(['Email'=>$v['Email'],'ID'=>$v['ID']],
array_combine(
array_column($contactDataArray[$k]['Data'],'Name'),
array_column($contactDataArray[$k]['Data'],'Value')
)
);
});
echo '<pre>';
print_r($res);
DEMO

Dynamically push arrays into multidimensional array

I'm trying to dynamically build an array for the Facebook Messenger SDK and populate it with data from a database.
I can't seem to get a properly structured array no matter what I try.
What I need:
$messages = [
"attachment" => [
"type" => "template",
"payload" => [
"template_type" => "generic",
"elements" => [[
"title" => $row['title'],
"item_url" => $row['item_url'],
"image_url" => $row['image_url'],
"subtitle" => $row['subtitle'],
"buttons" => [[
"type" => "web_url",
"url" => "www.google.com",
"title" => "View Website"],
["type" => "postback",
"title" => "Start Chatting",
"payload" => "start"]]
]
]]
]];
I need to create the data inside buttons based on what I have in the database, tried with array_merge and inserting the array as a string:
// Created arrays
if (!empty($row['button1_type'])) {
$buttons[] = array("type" => $row['button1_type'],"url" => $row['button1_url'],
"title" => $row['button1_title'],
"payload" => $row['button1_payload']);
}
if (!empty($row['button2_type'])) {
$buttons[] = array("type" => $row['button2_type'],"url" => $row['button2_url'],
"title" => $row['button2_title'],
"payload" => $row['button2_payload']);
}
// In the case when I had array_merge - $buttons were actually named as $buttons1 and $buttons2
$buttons = array_merge($buttons1, $buttons2);
// Tried to add it as a string
if (!empty($row['button2_type'])) {
$buttons = "\"type\" => ".$row['button2_type'].",\"url\" => .".$row['button2_url'].",
\"title\" => ".$row['button2_title'].",
\"payload\" => ".$row['button2_payload'];
}
$messages = [
"attachment" => [
"type" => "template",
"payload" => [
"template_type" => "generic",
"elements" => [[
"title" => $row['title'],
"item_url" => $row['item_url'],
"image_url" => $row['image_url'],
"subtitle" => $row['subtitle'],
"buttons" => [
$buttons
]
]
]]
]];
Screenshot showing the differences between correct and incorrect:
So basically $buttons are created inside an extra array, how can I get rid of it? Maybe I should change the whole approach?
With
"buttons" => [$buttons]
//new array ^ ^
a new array is being created with square brackets so to avoid it. use
"buttons" => $buttons

Merge two pairs in the same array if the pairs have the same value

I have the following pairs and they are in the same array:
[
["ID" => 0, "User" => "Test" , "Type" => 3, "Target" => "Caris"],
["ID" => 1, "User" => "Test1", "Type" => 3, "Target" => "Caris"],
["ID" => 2, "User" => "Test2", "Type" => 4, "Target" => "Shirone"],
["ID" => 3, "User" => "Test3", "Type" => 3, "Target" => "Caris"]
]
I want to get the kinds of them, so I using the following code:
$SortList = [];
foreach($Notif as $Key => $Value)
array_push($SortList, ['Type' => $Value['Type'],
'Target' => $Value['Target']]);
and get this:
[
["Type" => 3, "Target" => "Caris"],
["Type" => 3, "Target" => "Caris"],
["Type" => 4, "Target" => "Shirone"],
["Type" => 3, "Target" => "Caris"]
]
But what I really want is something like this:
[
["Type" => 3, "Target" => "Caris"],
["Type" => 4, "Target" => "Shirone"]
]
I want to merge the pairs if they were same value,
(array_merge() seems can only used for non-pair)
How can I merge them like something above?
$SortList = [];
foreach($Notif as $Key => $Value) {
// Just save only value for the same pair, use them concatenated as the key
$SortList[$Value['Type']."_".$Value['Target']] =
array('Type' => $Value['Type'], 'Target' => $Value['Target']);
}
// remove extra stuff (the keys) that was added to prevent duplicates
$SortList = array_values($SortList);

PHP - Creating tree node

I am working on a project that uses jQuery easy ui
I implemented the tree node but I encountered problems on it. I would like to use the drag and drop feature but I can't produce the right json string.
This is all I have.
This data was pulled from database :
<?php
$array = array( 0 => array(
"id" => 1,
"text" => "Root Dir",
"parent" => 0
),
1 => array(
"id" => 2,
"text" => "Folder one",
"parent" => 1
),
2 => array(
"id" => 3,
"text" => "Folder two",
"parent" => 2
),
3 => array(
"id" => 4,
"text" => "File",
"parent" => 3
)
);
?>
the final output should look like this
<?php
$array = array(
"id" => 1,
"text" => "Root Dir",
"children" => array(
"id" => 2,
"text" => "Folder one",
"children" => array(
"id" => 3,
"text" => "Folder one",
"children" => array(
"id" => 4,
"text" => "File"
)
)
)
);
print json_encode( $array );
?>
I am willing to adjust the database design if needed.

Categories