substr by using array as condition - php

I have a file contain text
ABBCDE1990-12-10JOBALPHABETabbcde1990-12-10jobalphabet
$field = array(
"fullname" => array("length"=5,"mandat"=>True),
"bithday" => array("length"=>10,"mandat"=>True)
"job" => array("length"=>3,"mandat"=>True),
"desc" => array("length"=>8,"mandat"=>false)
);
How can I get the array some thing like this:
$output = array(
//ABBCDE1990-12-10JOBALPHABET
0=>array(
"fullname" => "ABBCDE"
"bithday" => 1990-12-10
"job" => "JOB"
"desc"=> "ALPHABET"
)
//abbcde1990-12-10jobalphabet
1=>array(
"fullname" => "abbcde"
"bithday" => 1990-12-10
"job" => "job"
"desc"=> "alphabet"
)
);
I am tryin to buld a function
function toOutput($str,$filed){
$per_line = 27;//len of abbcde1990-12-10jobalphabet
$pos = 0;
while ($pos<strlen($str)){
$pos += 27;
//
}
}

$field = array(
"fullname" => array("length"=>6,"mandat"=>True),
"bithday" => array("length"=>10,"mandat"=>True),
"job" => array("length"=>3,"mandat"=>True),
"desc" => array("length"=>8,"mandat"=>false)
);
$string = 'ABBCDE1990-12-10JOBALPHABETabbcde1990-12-10jobalphabet';
$result = array();
$countString = strlen($string)/27;
$oldPos = 0;
for($i=0;$i<$countString;$i++) {
foreach($field as $k=>$v) {
$result[$i][$k] = substr($string,$oldPos,$v['length']);
$oldPos += $v['length'];
}
}
print_r($result);
You can see it up and running here: http://codepad.org/CEQNIPCg (version 0.3)
Based on that you can create a function so you can pass to it all $string that you have

Related

Intersection of one multidimensional arrays in PHP

I have the following array :
$output = array(
1507073550 => array(
0 => array(
"userid" => "1507073550"
"username" => "ma_alikhani"
"type" => "comment"
"profile_image" => "https://instagram.fgbb2-1.fna.fbcdn.net/v/t51.2885-19/s150x150/75538099_557824008392923_8054831368279949312_n.jpg?_nc_ht=instagram.fgbb2-1.fna.fbcdn.net&_nc_ohc"
)
1 => array(
"userid" => "11863258101"
"username" => "rasouli680"
"type" => "comment"
"profile_image" => "https://instagram.fgbb2-1.fna.fbcdn.net/v/t51.2885-19/s150x150/70326284_949495768737898_5241573836020776960_n.jpg?_nc_ht=instagram.fgbb2-1.fna.fbcdn.net&_nc_ohc"
)
2 => array(
"userid" => "16528062"
"username" => "alireza"
"type" => "comment"
"profile_image" => "https://instagram.fgbb2-1.fna.fbcdn.net/v/t51.2885-19/s150x150/70597112_740563976416368_5253996423334068224_n.jpg?_nc_ht=instagram.fgbb2-1.fna.fbcdn.net&_nc_ohc"
)
)
16528062 => array(
0 => array(
"userid" => "16528062"
"username" => "alireza"
"type" => "comment"
"profile_image" => "https://instagram.fgbb2-1.fna.fbcdn.net/v/t51.2885-19/s150x150/70597112_740563976416368_5253996423334068224_n.jpg?_nc_ht=instagram.fgbb2-1.fna.fbcdn.net&_nc_ohc"
)
1 => array(
"userid" => "1507073550"
"username" => "ma_alikhani"
"type" => "comment"
"profile_image" => "https://instagram.fgbb2-1.fna.fbcdn.net/v/t51.2885-19/s150x150/75538099_557824008392923_8054831368279949312_n.jpg?_nc_ht=instagram.fgbb2-1.fna.fbcdn.net&_nc_ohc"
)
)
)
and I want to intersection of keys of this array. get first key "1507073550" and second key "16528062" and intersect all of their data.
it's not always have 2 keys, it might have +2 keys, i wrote this code but I'm getting array to string conversion error.
$keys = array_keys($output);
foreach ($keys as $index => $values)
{
$current_value = $output[$values]; // or $current_value = $a[$keys[$index]];
$next_key = next($keys);
$next_value = $output[$next_key] ?? null; // for php version >= 7.0
$a[] = array_intersect_assoc($current_value,$next_value);
}
and I'm expecting this result :
array(
0 => array(
"userid" => "1507073550"
"username" => "ma_alikhani"
"type" => "comment"
"profile_image" => "https://instagram.fgbb2-1.fna.fbcdn.net/v/t51.2885-19/s150x150/75538099_557824008392923_8054831368279949312_n.jpg?_nc_ht=instagram.fgbb2-1.fna.fbcdn.net&_nc_ohc"
)
1 => array(
"userid" => "16528062"
"username" => "alireza"
"type" => "comment"
"profile_image" => "https://instagram.fgbb2-1.fna.fbcdn.net/v/t51.2885-19/s150x150/70597112_740563976416368_5253996423334068224_n.jpg?_nc_ht=instagram.fgbb2-1.fna.fbcdn.net&_nc_ohc"
)
)
I really don't know how to do it !
I'd be appreciated for your helps.
function intersect(array $src, array $keys)
{
// Require that both $src and $keys have data
if (!$src || !$keys) {
return [];
}
// Hold the users for each key in $keys
$sets = [];
// Store the users from $src to $sets as dictated by $keys
foreach ($keys as $key) {
if (isset($src[$key])) {
// Re-key the list of users with their user id
$userIds = array_column($src[$key], 'userid');
$sets[$key] = array_combine($userIds, $src[$key]);
}
}
if (count($sets) !== count($keys)) {
// Up to you if you want to require that all keys must be valid/present in the $src
}
// Get the users present in all of the set dictated by $keys
$users = call_user_func_array('array_intersect_key', $sets);
return $users;
};
To use:
$output = [ ... ]; // $ouput in the question
$keys = [1507073550, 16528062]; // see question
$users = intersect($output, $keys);

Extracting value from multidimensional array

$arrayDif = array();
$arrayDif[] = array('employer' => $employer,
'comment' => $comment,
'value' => $resultValue);
Filling in from a loop.
Below is the array that I have filled up. I need to be able to find a match by the 'employer' and 'comment' and extract the value, so I can re-update this value.
Array
(
[0] => Array
(
[employer] => Albury-Wodonga
[comment] => allOtherMembers
[value] => 7
)
[1] => Array
(
[employer] => Albury-Wodonga
[comment] => associateMembers
[value] => 1
)
One command to extract and re-update the value, I suggest to use foreach loop
<?php
$arrayDif = array();
$arrayDif[] = array('employer' => "AAA", 'comment' => "comment 1", 'value' => "1");
$arrayDif[] = array('employer' => "BBB", 'comment' => "comment 2", 'value' => "2");
$arrayDif[] = array('employer' => "CCC", 'comment' => "comment 3", 'value' => "3");
// function for setting the value or returning the value
// notice the $array here is a reference to the real array
function func(&$array, $employer, $comment, $value = ''){
// $v is also a reference
foreach ($array as $k => &$v) {
if($v['employer'] == $employer && $v['comment'] == $comment) {
if(empty($value)) {
return $v['value'];
} else {
$v['value'] = $value;
}
}
}
return "Not Found.";
}
//update
func($arrayDif, 'AAA', 'comment 1', "123123");
//search
echo func($arrayDif, 'AAA', 'comment 1');
?>
Not sure if this is what you are looking for but here you go. I would use a function and simple loop.
<?php
$arrayDif = array();
$arrayDif[] = array(
array('employer' => "Albury-Wodonga", 'comment' => "allOtherMembers", 'value' => "1 star"),
array('employer' => "Employer2", 'comment' => "Good Job", 'value' => "2 stars"),
array('employer' => "Employer3", 'comment' => "Smart", 'value' => "3 stars")
);
// Function for searching the array for the matches and returning the value of the match.
function SearchMe($array, $searchEmployer, $searchComment){
for($i = 0; $i < count($array); $i++){
for($j = 0; $j < count($array[$i]); $j++){
if(
$array[$i][$j]["employer"] == $searchEmployer &&
$array[$i][$j]["comment"] == $searchComment
){
return $array[$i][$j]["value"];
}
}
}
return "No Match";
}
echo SearchMe($arrayDif, "Albury-Wodonga", "allOtherMembers");
?>

Turn string to nested array php

I am trying to turn a string into a nested array
Here is my string:
a/b/d.docx
and I wanted to be like this:
array(
"name" => "a",
"type" => "folder",
"sub" => array(
"name" => "b",
"type" => "folder",
"sub" => array(
"name" => "c.docx",
"type" => "file",
"size" => "20"
)
)
)
This is the code that I have so far
$items = explode('/', $strings);
$num = count($items);
$num = --$num;
$temp = array();
foreach($items as $keys => $value) {
$temp[$keys] = array(
"name" => $value,
"type" => "folder",
"items" => $temp[++$keys]
);
if($keys == $num){
$temp[$keys] = array(
"name" => $value,
"type" => "file",
"size" => "20"
);
}
}
var_dump($temp);
I am trying this functions but this only turn string into a single array and it also can't do the 'items' line.
Any help would be appreciated.Thanks.
Note that the path is virtual and doesn't exist.
UPDATE: How can I add path to each array??for example,"path"=>"a/b"
You can do that:
$path = 'a/b/d.docx';
$parts = explode('/', $path);
$result = [ 'name' => array_pop($parts), 'type' => 'file', 'size' => 20 ];
while ($parts) {
$result = [ 'name' => array_pop($parts), 'type' => 'folder', 'sub' => $result ];
}
print_r($result);
<?php
$strings='a/b/d.docx';
$items = explode('/', $strings);
$num = count($items)-1;
$root= array();
$cur = &$root;
$v='';
foreach($items as $keys => $value) {
$v = $v.$value;
$temp = array( "name" => $value, "path"=>$v, "type" => "folder", "items" => "");
if($keys == $num){
$temp = array( "name" => $value, "path"=>$v, "type" => "file", "size" => "20");
}
$v= $v.'/';
if($keys==0) {
$cur = $temp;
}
else
{
$cur['items'] = $temp;
$cur = &$cur['items'];
}
}
var_dump($root);
Try recursion:
public function testAction(){
$sString = 'a/b/c/d.exe';
$aExploded = explode('/', $sString);
var_dump($this->_parse_folder_rec($aExploded));
}
private function _parse_folder_rec($aExploded){
$aResult = [];
$aResult['name'] = array_shift($aExploded);
if($aExploded){
$aResult['type'] = 'folder';
$aResult['sub'] = $this->_parse_folder_rec($aExploded);
}else{
$aResult['type'] = 'file';
$aResult['size'] = 20;
}
return $aResult;
}

Loop through array grouping indexes by value within that array (PHP)

I wish to create a list of items from an array, grouped by a value within that array.
Take this array:
$people = array(
0 => array(
"Forename" => "Jim",
"Surname" => "Smith"
),
1 => array(
"Forename" => "Mike",
"Surname" => "Johnson"
),
2 => array(
"Forename" => "Kim",
"Surname" => "Smith"
),
3 => array(
"Forename" => "Paul",
"Surname" => "Jones"
)
);
Specifically I'd like to run a foreach on $people, grouping them by unique surname. i.e. the desired output would be:
<select>
<optgroup label="Smith">
<option>Jim</option>
<option>Kim</option>
</optgroup>
<optgroup label="Johnson">
<option>Mike</option>
</optgroup>
<optgroup label="Jones">
<option>Paul</option>
</optgroup>
</select>
I'm struggling to come up with anything vaguely efficient and the Google gods aren't watching over me today :( What's the best approach for such a use-case in PHP?
$surnames = array();
foreach($people as $person) {
$surnames[$person['surname']][] = $person;
}
This code stores all persons in an array grouped by their surnames.
The resulting array:
array(
'smith' => array(
0 => array(
"Forename" => "Jim",
"Surname" => "Smith"
),
1 => array(
"Forename" => "Kim",
"Surname" => "Smith"
)
),
'jones' => array(
0 => array(
"Forename" => "Paul",
"Surname" => "Jones"
)
)
)
I would do this way:
$grouped = array();
foreach ($people as $p){
if (!array_key_exist($p["Surname"], $grouped)){
$grouped[$p["Surname"]] = array();
}
$grouped[$p["Surname"]][] = $p;
}
I've added one more duplicate person:
....
4 => array
(
"Forename" => "Kim",
"Surname" => "Smith"
)
);
this is how you filter array :
$uniqueNames = array();
foreach($people as $person)
{
$uniqueNames[$person['Surname']][] = $person['Forename'];
}
if however you also need Forename to be unique, you can do it like this:
$uniqueNames = array_map
(
function($arrayItem)
{
if (is_array($arrayItem))
{
return array_unique($arrayItem);
}
}
, $uniqueNames
);
Also I've made some easy functions to generate html code:
function htmlSelect($name, $optionsData, $selectedItem = null)
{
$str = "\n<select name='$name' id='select-$name'>";
foreach ($optionsData as $k => $value_s)
{
if(is_array($value_s))
{
$str .= htmlOptgroup($k, $value_s);
}
else
{
$selected = ($selectedItem && $selectedItem == $k);
$str .= "\n\t".htmlOption($value_s, $k, $selected);
}
}
$str .= "\n</select>";
return $str;
}
function htmlOptgroup($label, $optionsData, $selectedItem = null)
{
$str = "\n\t<optgroup label='$label'>";
foreach ($optionsData as $k => $value)
{
$selected = ($selectedItem && $selectedItem == $k);
$str .= "\n\t\t".htmlOption($value, $k, $selected);
}
$str .= "\n\t</optgroup>";
return $str;
}
function htmlOption($display, $value, $selected = false)
{
$selectedStr = $selected ? " selected='selected'" : "" ;
return "<option$selectedStr value='$value'>$display</option>";
}
these functions can easily move to static class for html.
finally you call:
echo htmlSelect('unique-surnames', $uniqueNames);
I swear when I started there was no any answers :d

Just cant get the for loop to produce needed array in Php

I need my for loop to return an array that looks like this
$nullArray =array(
0 => array("id" => 1, "label" => "test 1", "type" => "folder"),
array("id" => 2, "label" => "test 2", "type" => "folder"),
array("id" => 3, "label" => "test 3", "type" => "folder"),
etc...
etc...
etc...
);
what I have right now
$nullArray = array();
$numOfVer = mysql_num_rows($result);
$startArray= array();
//SETS FIRST NODE
for($i =0;$i < $numOfVer;$i++)
{
$label = mysql_result($result, $i);
$id = $i+1;
$startArray = array(array('id' => $id,'label' => $label, "type" => "folder"));
//$startArray[]['id'] = $id;
//$startArray[]['label'] = $label;
//$startArray[]['type'] = "folder";
//array_push($startArray,array(array('id' => $id,'label' => $label, "type" => "folder")));
//$nullArray[0]= array(array('id' => $id,'label' => $label, "type" => "folder"));
//array_push($nullArray[0],array('id' => $id,'label' => $label, "type" => "folder"));
}
$nullArray[0] = $startArray;
echo json_encode($nullArray[0]);
Everything that I have commented out is something that I have tried and it has failed. I'v been at it for too long for something so simple so I decided to get some help! Thank you in advance! :)
In for loop you are redclaring your $startArray thats why the previous value removed. Try this.
$nullArray = array();
$numOfVer = mysql_num_rows($result);
$startArray= array();
for($i =0;$i < $numOfVer;$i++)
{
$label = mysql_result($result, $i);
$id = $i+1;
$startArray[] = array('id' => $id,'label' => $label, "type" => "folder");
}

Categories