PHP - while creating array (mysql_fetch_array) program creating array in array - php

I want to create array:
$branza_query = mysql_query ('SELECT craft FROM base') or die...
$craft = array();
while ($cra = mysql_fetch_array($craft_query))
{
$craft[] = $cra;
}
No big deal but when i want to print_r it, i have restult like:
Array ( [0] => Array ( [0] => steel [craft] => steel )
[1] => Array ( [0] => farm [craft] => farm )
[2] => Array ( [0] => some [craft] => some )
[3] => Array ( [0] => it [craft] => it ) // etc.
)
I just wanted to add next value to existing array with result like:
Array ( [0] = steel
[1] = farm
[2] = some
[3] = it /etc.
)
or
Array ( [0] = craft => steel
[1] = craft => farm
[2] = craft => some
[3] = craft => it /etc.
)
or something similar because next thing what i want to do is something like:
foreach($craft as $value)
{
echo '<option value ="'.$value.'"> '.$value.'</option>';
}

The Problem is you create an array take $cra as its first element every time you call $craft[]=$cra, and then add it to $craft. That is why you have a three layer array as result.
But actually, $cra is already an array. So what you need to do is just array_push($craft, $cra);. Or use array_push($craft, $cra[0]); this will give what you want.
Please refer to the page http://php.net/manual/en/function.mysql-fetch-array.php

Related

Changing values of an array which consists of multiple objects

I would like to replace a value within the path array and I'm quite stuck for a while. So here is what I got.
My array:
// $myArr
Array
(
[0] => stdClass Object
(
[doc] => stdClass Object
(
[path] => Array
(
[0] => Bob
[1] => pictures
[2] => food
)
)
)
[1] => stdClass Object
(
[doc] => stdClass Object
(
[path] => Array
(
[0] => Alice
[1] => pictures
[2] => vacations
[3] => rome
)
)
)
)
PHP code:
for ($i=0; $i < count($myArr) ; $i++) {
$search = array($old_name); // pictures
$replace = array($new_name); // test
$result = str_replace($search, $replace, $myArr[$i]->doc->path);
}
Result:
It only changes one array and gives me a hint on my str_replace line. Both, $search and $replace are of type array and I know that I need to access elements in an array via array notation -> $item['price'] for example. That is not what is wrong here right?
Notice: Trying to get property of non-object in ...
Array
(
[0] => Bob
[1] => test
[2] => food
)
1) Do you see why he only modifies the last object so to speak?
2) Why is he giving me a Notice whereas I don't violate type conventions in my opinion?
Your code is working fine on my end, however..
I think the problem is in your $result variable. With every iteration, you are overwriting the last written value in the array.
You have to either use that $result variable directly, or replace $result by $myArr[$i]->doc->path. That way you can use the $myArr with the rewritten values.

Creating directories based on array values

I get a response from an API call that looks like the following
Array
(
[_id] => aasdasdasdasdasd
[created] => 2017-01-16T14:11:54.616Z
[options] => Array
(
[title] => 1
[data] => Array
(
[0] => Array
(
[labelName] => Date
[labelValues] => Array
(
[0] => March 2016
)
)
[1] => Array
(
[labelName] => Title
[labelValues] => Array
(
[0] => Food
)
)
[2] => Array
(
[labelName] => Product
[labelValues] => Array
(
[0] => Rice
)
)
)
)
)
I then process the response by doing the following
$results = array();
foreach ($output['options']['data'] as $data) {
if (isset($data['labelValues'][0])) {
$results[$data['labelName']] = $data['labelValues'][0];
}
}
This leaves me with something along the lines of this
Array
(
[Date] => March 2016
[Title] => Food
[Product] => Rice
)
Putting it into an array was not my intention, it was mainly done to help me better understand the looping required to process the original data.
My main intention is to create directories from these values. The main directory will be the Date, within this should be the Title and within this should be Product. So for the above, the directory structure should be something like 2016 > Food > Rice.
In order to achieve this, I have come up with the following
foreach ($output['options']['data'] as $data) {
if (isset($data['labelValues'][0])) {
if($data['labelName'] == 'Date') {
if (preg_match('/\b\d{4}\b/', $data['labelValues'][0], $matches)) {
$results[$data['labelName']] = $matches[0];
if (!file_exists($matches[0])) {
mkdir($matches[0], 0777, true);
}
}
}
}
}
The above works well and creates the date folder for me. Where I am struggling is how I now create the Title folder within the Date folder, and then the Product within the Title.
How would I go about achieving this?
Many thanks
I like your created array:
$array = array
(
[Date] => March 2016
[Title] => Food
[Product] => Rice
)
Simply implode the path:
mkdir(implode('/', $array), 0777, true);
This will create all of the directories, March 2016/Food/Rice

PHP Nested foreach with Key

I have been trying to work this out for two days now and am hitting a brick wall. I have a skyscanner array that has flight itineraries where I have the flight
Leg - being Itineraries -> OutboundLegId -
and also the legs which shows the flight number - being
Legs -> FlightNumbers -> FlightNumber.
What I am trying to achieve is to display the Itinerary and then join the Flight Number on to that. But no matter what I try I cannot get this to work. I have read all about Keys on here and tried loads of examples but am coming up with nothing. Can someone point me in the right direction please?
Example arrays below
[Itineraries] => Array
(
[0] => Array
(
[OutboundLegId] => 13542-1610140610-29-0-13445-1610141240
[InboundLegId] => 13445-1610211340-29-0-13542-1610211640
[PricingOptions] => Array
(
[0] => Array
(
[Agents] => Array
(
[0] => 2174187
)
[QuoteAgeInMinutes] => 31
[Price] => 200.98
[DeeplinkUrl] => http://partners.api.skyscanner.net/apiservices/deeplink/v2?_cje=5JlLCgyPUKY0hT8T0Ybh6dL0Xf0htAiHTFX7RU79eeI3XvrsxvEqP1QUJAoHiHRd&url=http%3a%2f%2fwww.apideeplink.com%2ftransport_deeplink%2f4.0%2fUK%2fen-gb%2fGBP%2fcook%2f2%2f13542.13445.2016-10-14%2c13445.13542.2016-10-21%2fair%2fairli%2fflights%3fitinerary%3dflight%7c-32294%7c1152%7c13542%7c2016-10-14T06%3a10%7c13445%7c2016-10-14T12%3a40%2cflight%7c-32294%7c1153%7c13445%7c2016-10-21T13%3a40%7c13542%7c2016-10-21T16%3a40%26carriers%3d-32294%26passengers%3d1%2c0%2c0%26channel%3ddataapi%26cabin_class%3deconomy%26facilitated%3dfalse%26ticket_price%3d200.98%26is_npt%3dfalse%26is_multipart%3dfalse%26client_id%3dskyscanner_b2b%26request_id%3d3bc96bda-fd7c-403a-b841-2ccc3c26071d%26commercial_filters%3dfalse%26q_datetime_utc%3d2016-09-29T08%3a18%3a27
)
[Legs] => Array
(
[0] => Array
(
[Id] => 13542-1610140610-29-0-13445-1610141240
[SegmentIds] => Array
(
[0] => 1
)
[OriginStation] => 13542
[DestinationStation] => 13445
[Departure] => 2016-10-14T06:10:00
[Arrival] => 2016-10-14T12:40:00
[Duration] => 270
[JourneyMode] => Flight
[Stops] => Array
(
)
[Carriers] => Array
(
[0] => 105
)
[OperatingCarriers] => Array
(
[0] => 105
)
[Directionality] => Outbound
[FlightNumbers] => Array
(
[0] => Array
(
[FlightNumber] => 1152
[CarrierId] => 105
)
)
)
Assuming this is one big array and its called $data you can nest a couple of foreach loops.
I use foreach loops as I assume there are cases where this data structure get more complex than the one you show
foreach ( $data['Itineraries'] as $itin ) {
foreach ( $data['Legs'] as $legs) {
if ($legs['Id'] == $itin['OutboundLegId']) {
// we matched the itinerary with a leg
echo $legs['OutboundLegId'] . ' ' . $legs['FlightNumbers'][0]['FlightNumber'];
}
}
}
Use it as draft. Can't perform function without feedback.
Put proper arrays instead of {YOUR-ARRAY-WITH-LEGS} and {YOUR-ARRAY-WITH-ITINERARIES}
$sortedLegs = array_column('Id', {YOUR-ARRAY-WITH-LEGS});
$joinedArray = array_map(function($itinerary) use($sortedLegs){
if(array_key_exists($itinerary['OutboundLegId'],$sortedLegs)) {
$itinerary['legs'] = $sortedLegs[$itinerary['OutboundLegId']];
}
return $itinerary;
},{YOUR-ARRAY-WITH-ITINERARIES});

Efficiently transforming Arrays (PHP)

Edit: Thanks to #Felix Kling and #mario for pointing me towards named capture groups and PREG_SET_ORDER, I totally learned something today.
I'm curious about a better algorithm per se, though. So please just pretend that there's no preg_match() involved.
Edit 2: Abstracted question
While answering another question here, I stumbled upon the fact that my code for turning
this:
Array
(
[0] => Array (
[0] => 1
[1] => 3
)
[1] => Array (
[0] => Description text
[1] => Different Description text
)
[2] => Array (
[0] => 123.456.12
[1] => 234.567.89
)
[3] => Array (
[0] => 10.00
[1] => 10.00
)
[4] => Array (
[0] => 10.00
[1] => 30.00
)
)
into that:
Array
(
[0] => Array
(
[qty] => 1
[description] => "Description text"
[sku] => 123.456.12
[price] => 10.00
[total] => 10.00
)
…
)
is fugly:
$field_names = array('qty', 'description', 'sku', 'price', 'total');
$result_arr = array();
$num_iter = count(matches[0]);
for ($i = 0; $i < $num_iter; $i++) {
foreach ($field_names as $index => $field_name) {
$result_arr[$i][$field_name] = array_shift($input_arr[$index]);
}
}
Any suggestions for improvement?
There is one simpler way to produce the desired output.
while (count($input_arr[0])) {
$values = array_map("array_shift", & $input_arr);
$result_arr[] = array_combine($field_names, $values);
}
This won't work past PHP 5.3, as it requires forcibly passing a parameter by reference. (Avoiding any dumbing-down-the-language remarks here). But you can of course chop off the entries with a more elaborate manual loop at any time.
The real simplification for such cases is however array_combine to turn a list into an associative array.

PHP array_push() - pushing new data to array

I have an array which looks like this:
Array
(
[0] => Array
(
[1] => Array
(
[name] => vrij
// ...
)
[2] => Array
(
[name] => zat
// ...
)
)
)
I build this array using a for loop; however, I need to push 4 more 'records' to the array, which I can't do in this for loop.
I want the array to look like this, after the pushes:
Array
(
[0] => Array
(
[1] => Array
(
[name] => vrij
// ...
)
[2] => Array
(
[name] => zat
// ...
)
// ...
)
[1] => Array
(
[1] => Array
(
[name] => zon
//...
)
[2] // etc
)
)
The four new records should be pushed to array[1], so I get something like
$array[1][0], $array[1][1], etc. 0 1 2 3 contains the new data.
I tried quite a lot of stuff, to be honest. I need to do four of these pushes, so I was trying a for loop:
for($i = 0; $i < 4; $i++)
{
$day_info = $this->get_day_info($i, $data['init']['next_month'], $data['init']['current_year']);
$push['name'] = $day_info['day_name'];
array_push($data['dates'], $push);
}
and all other kinds of things with [], [1][$i], etc. Sometimes it even adds five arrays! I'm confused as to why it won't just add the [1][1], [1][2],.. I'm probably missing out on something here. Thanks a lot.
If this isn't clear, please do tell and I'll add more code to explain the problem better.
$extradates = array(1 => 'zon', 2 => 'maa');
$data['dates'][] = $extradates;
Will add 2 extra dates to the array using a new index.
Although if I see what you trying to accomplish, I think there might be a better way.
This above works though :)

Categories