PHP Explode String Into Multiple Arrays - php

I have the following string: "1,3,4,7" which I need to explode into an Array in the following format:
$data = array(
array(
'id' => 1
),
array(
'id' => 3
),
array(
'id' => 4
),
array(
'id' => 7
),
);
This seems to be causing me a lot more pain than I'd have thought. Can anyone kindly assist please?

You can use a combination of array_map() and explode(): First you create an array with the values and than you map all these values to the format you need in a new array.
Something like:
$vals = "1,3,4,7";
$map = array_map(function($val) {
return array('id' => $val);
}, explode(',', $vals));
var_dump($map);
An example.

Firstly you explode the string to get the values in an array. Then you iterate through the array and set the data as array to another array
$string = "1,2,3,4";
$array = explode(",", $string);
$data = array();
foreach($array as $arr){
$data[] = array('id' => $arr);
}

<?php
$myArray=explode(",","1,3,5,7");
$result=array();
foreach($myArray as $key=>$arr)
{
$result[$key]['id']=$arr;
}
print_r($result);
?>

Here is a thinking-outside-the-box technique that doesn't require a loop or iterated function calls.
Form a valid query string with the desired structure and parse it. The empty [] syntax will generate the indexes automatically.
Code: (Demo)
$vals = "1,3,4,7";
$queryString = 'a[][id]=' . str_replace(',', '&a[][id]=', $vals);
parse_str($queryString, $output);
var_export($output['a']);
Output:
array (
0 =>
array (
'id' => '1',
),
1 =>
array (
'id' => '3',
),
2 =>
array (
'id' => '4',
),
3 =>
array (
'id' => '7',
),
)

Related

Multidimensional Array - Match by odd key

I am trying to find the difference of 2 multidimensional arrays. I am attempting to solve this with a modified recursive array difference function.
If I have the following array setup:
$array1 = array(
0 => array(
'Age' => '1004',
'Name' => 'Jack'
),
1 => array (
'Age' => '1005',
'Name' => 'John'
)
);
$array2 = array(
0 => array(
'Age_In_Days' => '1004',
'Name' => 'Jack'
),
1=> array(
'Transaction_Reference' => '1005',
'Name' => 'Jack'
)
);
I am trying to match the arrays however the keys are not the same. I want to return the difference between the two multidimensional arrays where
$array1[$i]['Age'] == $array2[$i]['Age_In_Days'];
I want to keep the original array structure if the above condition holds true so the output I am looking for is:
$diff = array (1 => array (
'Age' => '1005',
'Name' => 'John'
));
However I am having issues with how to modify the recursive function to achieve this. Any help is appreciated! Thanks!
You need to loop through first array and compare values with second array. Then follows your condition. If condition is true then push this unique value to third array. Values in third array are now diff between first and second array.
$diff = [];
foreach ($array1 as $value1) {
foreach ($array2 as $value2) {
if ($value1['Age'] !== $value2['Age_In_Days']) {
array_push($diff, $value1);
}
}
}

Laravel/PHP create an array from array

Hey guys I'm confused about how to create an array using specific keys from my pre-existing array.
Laravel controller
public function index()
{
$content = Page::find(1)->content->toArray();
return View::make('frontend.services', compact('content'));
}
$content is an array that looks similar to
array (
0 => array (
'id' => '1',
'page_id' => '1',
'name' => 'banner_heading',
'content' => 'some content', ),
1 => array (
'id' => '2',
'page_id' => '1',
'name' => 'banner_text',
'content' => 'some other content' )
)
And I want it recreate this array to look like this
array (
0 => array (
'banner_heading' => 'some content'
),
1 => array (
'banner_text' => 'some other content'
)
)
How can I move the keys name and content to equal their values as a single row in the array?
I greatly appreciate any advice.
PHP >= 5.5.0:
$result = array_column($content, 'content', 'name');
PHP < 5.5.0:
foreach($content as $key => $array) {
$result[$key] = array($array['name'] => $array['content']);
}
You mean
$newContent = array();
foreach ($content as $record) {
$newContent[] = array($record['name'] => $record['content']);
}
?
I don't know Laravel, but i believe that your solutions should be similar to this :
$newArray= array();
foreach($content as $key => $value)
{
$newArray[] = $value["banner_heading"];
}
return View::make('frontend.services', compact('newArray'));
Or at least it should be something similar with this.

PhP multidimensional array to individual array

I have a multidimensional array which I want to convert to individual arrays.
Original array is
$hos_pabsl = array(
0 =>
array(
'tile_id' => '1',
'tile_type' => '4',
'title' => 'Introduction',
'topicNum' => '1',
'topicTitle' => 'Introduction',
'subNum' => NULL,
),
1 =>
array(
'tile_id' => '2',
'tile_type' => '9',
'title' => 'Beer',
'topicNum' => '2',
'topicTitle' => 'Beer',
'subNum' => NULL,
),
2 =>
array(
'tile_id' => '3',
'tile_type' => '4',
'title' => 'Methods of Brewing',
'topicNum' => '2',
'topicTitle' => 'Beer',
'subNum' => NULL,
),
3 =>
array(
'tile_id' => '4',
'tile_type' => '11',
'title' => 'Beer Styles',
'topicNum' => '2',
'topicTitle' => 'Beer',
'subNum' => '',
),
);
I want to convert this array into individual arrays named 'tile_id' , 'tile_type' , ....
Currently I am doing it the following way !
$tile_id = [];
$tile_type = [];
$title = [];
$topicNum = [];
$topicTitle= [];
$subNum = [];
foreach($hos_pabsl as $val){
array_push($tile_id, $val['tile_id']);
array_push($tile_type, $val['tile_type']);
array_push($title, $val['title']);
array_push($topicNum, $val['topicNum']);
array_push($topicTitle, $val['topicTitle']);
array_push($subNum, $val['subNum']);
}
Problem 1: IS this the most efficient way (in terms of speed) to do this operation?
Problem 2:
The $hos_pabsl array's index (or keys) are always going to be sequential. However, my problem is that for second array (at level 2 OR $hos_pabsl[0]) the index (or keys) might increase or decrease.
E.g. all arrays in might have only 2 items 'tile_id' & 'title'. OR might have one extra item 'description'. So how can I make the above operation dynamic ?
To Solve problem 2, I have thought of using array_keys to extract names first $names = array_keys($hos_pabsl[0]) then using those names as array names like ${$names[0]} =[]. Again I don't think this is the right/efficient way to do this.
Any guidance on this would be really appreciated.
If you're running PHP 5.5, then you can use array_column()
$tile_id = array_column($hos_pabsl, 'tile_id');
$tile_type = array_column($hos_pabsl, 'tile_type');
... etc
for versions of PHP earlier than 5.5, you can use array_map()
$tile_id = array_map(
function ($value) { return $value['tile_id']; }, $hos_pabsl
);
$tile_type = array_map(
function ($value) { return $value['tile_type']; }, $hos_pabsl
);
... etc
To go with Mark Baker's answer since I was already typing it:
foreach(array_keys(reset($hos_pabsl)) as $key) {
$$key = array_column($hos_pabsl, $key);
}
In terms of performance if the array is huge using a for instead of a foreach it will be faster.
$tile_id = array();
$tile_type = array();
$title = array();
$topicNum = array();
$topicTitle = array();
$subNum = array();
$hos_pabsl_sz = count($hos_pabsl);
for ($i = 0; $i < $hos_pabsl_sz; ++$i ) {
$tile_id[$i] = $hos_pabsl[$i]['tile_id'];
$tile_type[$i] = $hos_pabsl[$i]['tile_type'];
$title[$i] = $hos_pabsl[$i]['title'];
$topicNum[$i] = $hos_pabsl[$i]['topicNum'];
$topicTitle[$i] = $hos_pabsl[$i]['topicTitle'];
$subNum[$i] = $hos_pabsl[$i]['subNum'];
}

Get path and value of all elements in nested associative array

Consider an associative array of arbitrary form and nesting depth, for example:
$someVar = array(
'name' => 'Dotan',
'age' => 35,
'children' => array(
0 => array(
'name' => 'Meirav',
'age' => 6,
),
1 => array(
'name' => 'Maayan',
'age' => 4,
)
),
'dogs' => array('Gili', 'Gipsy')
);
I would like to convert this to an associative array of paths and values:
$someVar = array(
'name' => 'Dotan',
'age' => 35,
'children/0/name' => 'Meirav',
'children/0/age' => 6,
'children/1/name' => 'Maayan',
'children/1/age' => 4,
'dogs/0' => 'Gili',
'dogs/1' => 'Gipsy'
);
I began writing a recursive function which for array elements would recurse and for non-array elements (int, floats, bools, and strings) return an array $return['path'] and $return['value']. This got sloppy quick! Is there a better way to do this in PHP? I would assume that callables and objects would not be passed in the array, though any solution which deals with that possibility would be best. Also, I am assuming that the input array would not have the / character in an element name, but accounting for that might be prudent! Note that the input array could be nested as deep as 8 or more levels deep!
Recursion is really the only way you'll be able to handle this, but here's a simple version to start with:
function nested_values($array, $path=""){
$output = array();
foreach($array as $key => $value) {
if(is_array($value)) {
$output = array_merge($output, nested_values($value, (!empty($path)) ? $path.$key."/" : $key."/"));
}
else $output[$path.$key] = $value;
}
return $output;
}
function getRecursive($path, $node) {
if (is_array($node)) {
$ret = '';
foreach($node as $key => $val)
$ret .= getRecursive($path.'.'.$key, $val);
return $ret;
}
return $path.' => '.$node."\n";
}
$r = getRecursive('', $someVar);
print_r($r);
All yours to place it in an array.

PHP: how to create associative array by key?

I have simple array
array(
array( 'id'=>5, 'something' => 2, 'dsadsa' => 'fsfsd )
array( 'id'=>20, 'something' => 2, 'dsadsa' => 'fsfsd )
array( 'id'=>30, 'something' => 2, 'dsadsa' => 'fsfsd )
)
How to create associative array by id field (or something else) from it in the right way?
array(
'5' => array( 'something' => 2, 'dsadsa' => 'fsfsd )
'20' => array( 'something' => 2, 'dsadsa' => 'fsfsd )
'30' => array( 'something' => 2, 'dsadsa' => 'fsfsd )
)
Something along these lines.
$new_array = array();
foreach ($original_array as &$slice)
{
$id = (string) $slice['id'];
unset($slice['id']);
$new_array[$id] = $slice;
}
#NikitaKuhta, nope. There is no slice function which returns a column of values in a 2D keyed table associated with a given key or column heading. You can use some of the callback array_... functions, but you will still need to execute a custom function per element so its just not worth it. I don't like Core Xii's solution as this corrupts the original array as a side effect. I suggest that you don't use references here:
$new_array = array();
foreach ($original_array as $slice) {
$id = (string) $slice['id'];
unset($slice['id']);
$new_array[$id] = $slice;
}
# And now you don't need the missing unset( $slice)

Categories